/**
 * WhatsApp Greeting Form
 *
 * Lets organization owners configure the welcome message customers see the
 * first time they message the business on WhatsApp. The form mirrors the
 * styling used elsewhere in the dashboard (slate palette, rounded-xl cards).
 *
 * Behavior:
 * - Loads current greeting fields from `/api/dashboard/whatsapp-greeting`
 * - Persists changes via PATCH on the same endpoint (CSRF-protected)
 * - Owners can opt out of automatic greetings entirely via the toggle
 * - Leaving the message fields blank reverts to the default bilingual prompt
 *
 * Used by: components/dashboard/knowledge-base/KnowledgeBasePanel.tsx
 */

"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  CheckCircle2,
  Loader2,
  MessageSquareText,
  Save,
} from "lucide-react";

interface WhatsAppGreetingFormProps {
  organizationId: string;
  lang: "en" | "ar";
}

interface GreetingResponse {
  success: boolean;
  greetingMessageEn?: string | null;
  greetingMessageAr?: string | null;
  autoGreetingEnabled?: boolean;
  error?: string;
}

const MAX_GREETING_LENGTH = 2000;

export default function WhatsAppGreetingForm({
  organizationId,
  lang,
}: WhatsAppGreetingFormProps) {
  const isAr = lang === "ar";
  const dir: "rtl" | "ltr" = isAr ? "rtl" : "ltr";

  const t = useMemo(
    () => ({
      title: isAr ? "رسالة الترحيب على واتساب" : "WhatsApp Welcome Message",
      subtitle: isAr
        ? "خصّص أول رسالة يشوفها عملاؤك لما يكلمونك على واتساب"
        : "Customize the first message customers see when they reach out on WhatsApp",
      autoToggleLabel: isAr
        ? "إرسال رسالة ترحيب تلقائية"
        : "Send automatic welcome message",
      autoToggleHint: isAr
        ? "لو طفّيتها، ما رح نرسل أي ترحيب وراح ندخل العميل مباشرة بالمحادثة"
        : "Turn off to skip the welcome message and start the conversation immediately",
      enLabel: isAr ? "رسالة الترحيب (إنجليزي)" : "Welcome message (English)",
      arLabel: isAr ? "رسالة الترحيب (عربي)" : "Welcome message (Arabic)",
      enPlaceholder: isAr
        ? "مثلاً: Welcome to our clinic! How can we help you today?"
        : "e.g. Welcome to our clinic! How can we help you today?",
      arPlaceholder: isAr
        ? "مثلاً: هلا والله بعيادتنا! شلون نقدر نساعدك اليوم؟"
        : "e.g. هلا والله بعيادتنا! شلون نقدر نساعدك اليوم؟",
      helpText: isAr
        ? "رسالة الترحيب تُعرض لما يكلمك العميل لأول مرة. بنضيف تلقائياً سؤال اختيار اللغة في النهاية. خلّها فاضية لو تبي تستخدم الترحيب الافتراضي."
        : "Your welcome message is shown when a customer messages you for the first time. We'll automatically append a language selection prompt at the end. Leave blank to use the default.",
      save: isAr ? "حفظ التغييرات" : "Save changes",
      saving: isAr ? "جارٍ الحفظ..." : "Saving...",
      saved: isAr ? "تم الحفظ" : "Saved",
      loading: isAr ? "جارٍ التحميل..." : "Loading...",
      errorLoading: isAr
        ? "تعذّر تحميل إعدادات الترحيب"
        : "Couldn't load greeting settings",
      errorSaving: isAr
        ? "فشل الحفظ، جرّب مرة ثانية"
        : "Failed to save, please try again",
      charsRemaining: isAr ? "حرف متبقّي" : "characters remaining",
    }),
    [isAr],
  );

  // ── State ─────────────────────────────────────────────────────────────────
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [savedAt, setSavedAt] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [csrfToken, setCsrfToken] = useState("");

  const [autoGreetingEnabled, setAutoGreetingEnabled] = useState(true);
  const [greetingMessageEn, setGreetingMessageEn] = useState("");
  const [greetingMessageAr, setGreetingMessageAr] = useState("");

  // ── Fetch CSRF token ──────────────────────────────────────────────────────
  useEffect(() => {
    let cancelled = false;
    fetch("/api/csrf")
      .then((res) => res.json())
      .then((json) => {
        if (!cancelled && json?.csrfToken) {
          setCsrfToken(json.csrfToken as string);
        }
      })
      .catch((err) => {
        console.error("Failed to fetch CSRF token", err);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // ── Load current greeting ─────────────────────────────────────────────────
  const load = useCallback(async () => {
    if (!organizationId) return;
    setLoading(true);
    setError(null);

    try {
      const res = await fetch(
        `/api/dashboard/whatsapp-greeting?organizationId=${encodeURIComponent(
          organizationId,
        )}`,
        { cache: "no-store" },
      );

      if (!res.ok) {
        throw new Error(`Request failed: ${res.status}`);
      }

      const json = (await res.json()) as GreetingResponse;
      setAutoGreetingEnabled(json.autoGreetingEnabled ?? true);
      setGreetingMessageEn(json.greetingMessageEn ?? "");
      setGreetingMessageAr(json.greetingMessageAr ?? "");
    } catch (err) {
      console.error("Failed to load greeting", err);
      setError(t.errorLoading);
    } finally {
      setLoading(false);
    }
  }, [organizationId, t.errorLoading]);

  useEffect(() => {
    load();
  }, [load]);

  // Auto-clear "saved" state after a few seconds
  useEffect(() => {
    if (!savedAt) return;
    const timer = window.setTimeout(() => setSavedAt(null), 3000);
    return () => window.clearTimeout(timer);
  }, [savedAt]);

  // ── Save handler ──────────────────────────────────────────────────────────
  const handleSave = useCallback(async () => {
    if (!organizationId || !csrfToken) return;
    setSaving(true);
    setError(null);

    try {
      const res = await fetch("/api/dashboard/whatsapp-greeting", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          organizationId,
          greetingMessageEn: greetingMessageEn.trim() || null,
          greetingMessageAr: greetingMessageAr.trim() || null,
          autoGreetingEnabled,
        }),
      });

      if (!res.ok) {
        throw new Error(`Request failed: ${res.status}`);
      }

      setSavedAt(Date.now());
    } catch (err) {
      console.error("Failed to save greeting", err);
      setError(t.errorSaving);
    } finally {
      setSaving(false);
    }
  }, [
    autoGreetingEnabled,
    csrfToken,
    greetingMessageAr,
    greetingMessageEn,
    organizationId,
    t.errorSaving,
  ]);

  const enRemaining = MAX_GREETING_LENGTH - greetingMessageEn.length;
  const arRemaining = MAX_GREETING_LENGTH - greetingMessageAr.length;

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <section
      dir={dir}
      className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
      aria-label={t.title}
    >
      {/* Header */}
      <div className="mb-5 flex items-start gap-3">
        <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-emerald-50">
          <MessageSquareText className="h-5 w-5 text-emerald-600" aria-hidden="true" />
        </div>
        <div className="flex-1">
          <h3 className="text-lg font-semibold text-slate-900">{t.title}</h3>
          <p className="mt-0.5 text-sm text-slate-500">{t.subtitle}</p>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-10 text-sm text-slate-500">
          <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
          {t.loading}
        </div>
      ) : (
        <div className="space-y-5">
          {/* Auto greeting toggle */}
          <div className="flex items-start justify-between gap-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
            <div className="flex-1">
              <p className="font-medium text-slate-900">{t.autoToggleLabel}</p>
              <p className="mt-1 text-xs text-slate-500">{t.autoToggleHint}</p>
            </div>
            <button
              type="button"
              role="switch"
              aria-checked={autoGreetingEnabled}
              onClick={() => setAutoGreetingEnabled((v) => !v)}
              disabled={saving}
              className={`relative inline-flex h-6 w-11 flex-shrink-0 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 disabled:opacity-50 ${
                autoGreetingEnabled ? "bg-emerald-600" : "bg-slate-300"
              }`}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                  autoGreetingEnabled ? "translate-x-6" : "translate-x-1"
                }`}
              />
            </button>
          </div>

          {/* Help text */}
          <p className="text-xs text-slate-500">{t.helpText}</p>

          {/* English message */}
          <div>
            <label
              htmlFor="whatsapp-greeting-en"
              className="mb-2 block text-sm font-medium text-slate-700"
            >
              {t.enLabel}
            </label>
            <textarea
              id="whatsapp-greeting-en"
              value={greetingMessageEn}
              onChange={(e) =>
                setGreetingMessageEn(
                  e.target.value.slice(0, MAX_GREETING_LENGTH),
                )
              }
              placeholder={t.enPlaceholder}
              dir="ltr"
              rows={4}
              maxLength={MAX_GREETING_LENGTH}
              disabled={saving || !autoGreetingEnabled}
              className="w-full rounded-xl border-2 border-slate-200 px-4 py-2.5 text-sm text-slate-900 placeholder-slate-400 transition-colors focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 disabled:cursor-not-allowed disabled:bg-slate-50 disabled:text-slate-400"
            />
            <p className="mt-1 text-xs text-slate-400">
              {enRemaining} {t.charsRemaining}
            </p>
          </div>

          {/* Arabic message */}
          <div>
            <label
              htmlFor="whatsapp-greeting-ar"
              className="mb-2 block text-sm font-medium text-slate-700"
            >
              {t.arLabel}
            </label>
            <textarea
              id="whatsapp-greeting-ar"
              value={greetingMessageAr}
              onChange={(e) =>
                setGreetingMessageAr(
                  e.target.value.slice(0, MAX_GREETING_LENGTH),
                )
              }
              placeholder={t.arPlaceholder}
              dir="rtl"
              rows={4}
              maxLength={MAX_GREETING_LENGTH}
              disabled={saving || !autoGreetingEnabled}
              className="w-full rounded-xl border-2 border-slate-200 px-4 py-2.5 text-sm text-slate-900 placeholder-slate-400 transition-colors focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 disabled:cursor-not-allowed disabled:bg-slate-50 disabled:text-slate-400"
            />
            <p className="mt-1 text-xs text-slate-400">
              {arRemaining} {t.charsRemaining}
            </p>
          </div>

          {/* Error banner */}
          {error && (
            <div
              role="alert"
              className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700"
            >
              {error}
            </div>
          )}

          {/* Action row */}
          <div className="flex items-center justify-between gap-3 pt-2">
            <div className="flex items-center gap-2 text-sm text-emerald-600">
              {savedAt && (
                <>
                  <CheckCircle2 className="h-4 w-4" aria-hidden="true" />
                  <span>{t.saved}</span>
                </>
              )}
            </div>
            <button
              type="button"
              onClick={handleSave}
              disabled={saving || !csrfToken}
              className="inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {saving ? (
                <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
              ) : (
                <Save className="h-4 w-4" aria-hidden="true" />
              )}
              {saving ? t.saving : t.save}
            </button>
          </div>
        </div>
      )}
    </section>
  );
}
