/**
 * Twilio WhatsApp Credentials Form
 *
 * Lets organization owners paste their Twilio Account SID, Auth Token,
 * and WhatsApp number from the dashboard. Renders inside the WhatsApp
 * setup wizard as the alternative to the Meta credentials path.
 *
 * Also displays the public webhook URL the owner needs to paste into
 * the Twilio console under "When a message comes in" so they can wire
 * the inbound message flow.
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  ChevronLeft,
  ChevronRight,
  Copy,
  Check,
  Loader2,
  ExternalLink,
  AlertCircle,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { useOrganizationRole } from "@/components/dashboard/hooks/useOrganizationRole";

interface TwilioCredentialsFormProps {
  lang: Lang;
  onSuccess: (data: { displayNumber?: string; businessName?: string }) => void;
  onBack: () => void;
}

interface ServerState {
  configured: boolean;
  twilioAccountSid: string;
  twilioAuthTokenMasked: string;
  twilioWhatsappNumber: string;
  webhookUrl: string;
}

export default function TwilioCredentialsForm({
  lang,
  onSuccess,
  onBack,
}: TwilioCredentialsFormProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";
  const { organizationId } = useOrganizationRole();

  const [csrfToken, setCsrfToken] = useState("");
  const [server, setServer] = useState<ServerState | null>(null);
  const [loading, setLoading] = useState(true);

  // Form state
  const [accountSid, setAccountSid] = useState("");
  const [authToken, setAuthToken] = useState("");
  const [whatsappNumber, setWhatsappNumber] = useState("");

  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [copied, setCopied] = useState(false);

  const t = {
    title: isAr
      ? "ربط واتساب عبر Twilio"
      : "Connect WhatsApp via Twilio",
    subtitle: isAr
      ? "ادخل بيانات حساب Twilio الخاص بك"
      : "Enter your Twilio account credentials",
    accountSidLabel: isAr ? "Account SID" : "Account SID",
    accountSidHelp: isAr
      ? "يبدأ بـ AC ويتكون من ٣٤ حرف"
      : "Starts with AC, 34 characters total",
    authTokenLabel: isAr ? "Auth Token" : "Auth Token",
    authTokenHelp: isAr
      ? "موجود في لوحة تحكم Twilio بجانب Account SID"
      : "Found in your Twilio Console next to Account SID",
    whatsappNumberLabel: isAr
      ? "رقم واتساب على Twilio"
      : "Twilio WhatsApp Number",
    whatsappNumberHelp: isAr
      ? "بصيغة E.164 مثل +14155238886. لا تضف whatsapp: في البداية."
      : "E.164 format like +14155238886. Do not include the whatsapp: prefix.",
    sandboxHint: isAr
      ? "للاختبار، استخدم رقم Twilio Sandbox: +14155238886"
      : "For testing, use the Twilio Sandbox number: +14155238886",
    webhookSection: isAr
      ? "ضع هذا الرابط في إعدادات Twilio"
      : "Paste this URL into Twilio",
    webhookHelp: isAr
      ? "افتح Twilio Console ← Messaging ← Try it out ← Send a WhatsApp message ← Sandbox settings ← \"When a message comes in\""
      : "Open Twilio Console → Messaging → Try it out → Send a WhatsApp message → Sandbox settings → \"When a message comes in\"",
    methodPost: isAr ? "الطريقة: POST" : "Method: POST",
    copy: isAr ? "نسخ" : "Copy",
    copied: isAr ? "تم النسخ" : "Copied",
    openTwilio: isAr ? "افتح Twilio Console" : "Open Twilio Console",
    save: isAr ? "حفظ البيانات" : "Save Credentials",
    saving: isAr ? "جارٍ الحفظ..." : "Saving...",
    back: isAr ? "رجوع" : "Back",
    successMsg: isAr
      ? "تم حفظ البيانات بنجاح"
      : "Credentials saved successfully",
    loadingOrg: isAr ? "جارٍ التحميل..." : "Loading...",
    noOrg: isAr
      ? "لم نجد منظمة لربطها"
      : "No organization found to attach credentials to",
  };

  // Fetch CSRF token on mount
  useEffect(() => {
    fetch("/api/csrf")
      .then((r) => r.json())
      .then((j) => {
        if (j?.csrfToken) setCsrfToken(j.csrfToken as string);
      })
      .catch(() => {
        // Non-fatal — save will fail later with a clear error
      });
  }, []);

  // Load existing credentials
  const loadCredentials = useCallback(async () => {
    if (!organizationId) return;
    setLoading(true);
    try {
      const res = await fetch(
        `/api/dashboard/twilio-credentials?organizationId=${encodeURIComponent(organizationId)}`,
        { credentials: "include" },
      );
      const data = await res.json();
      if (res.ok && data.success !== false) {
        setServer({
          configured: !!data.configured,
          twilioAccountSid: data.twilioAccountSid ?? "",
          twilioAuthTokenMasked: data.twilioAuthTokenMasked ?? "",
          twilioWhatsappNumber: data.twilioWhatsappNumber ?? "",
          webhookUrl: data.webhookUrl ?? "",
        });
        setAccountSid(data.twilioAccountSid ?? "");
        setWhatsappNumber(data.twilioWhatsappNumber ?? "");
      }
    } catch {
      // Non-fatal
    } finally {
      setLoading(false);
    }
  }, [organizationId]);

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

  const handleCopyWebhook = () => {
    if (!server?.webhookUrl) return;
    navigator.clipboard
      .writeText(server.webhookUrl)
      .then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      })
      .catch(() => {
        /* clipboard failures are silent */
      });
  };

  const handleSave = async () => {
    setError("");

    if (!organizationId) {
      setError(t.noOrg);
      return;
    }
    if (!accountSid.trim()) {
      setError(isAr ? "Account SID مطلوب" : "Account SID is required");
      return;
    }
    if (!authToken.trim()) {
      setError(isAr ? "Auth Token مطلوب" : "Auth Token is required");
      return;
    }
    if (!whatsappNumber.trim()) {
      setError(
        isAr ? "رقم واتساب مطلوب" : "WhatsApp number is required",
      );
      return;
    }

    setSaving(true);
    try {
      const res = await fetch("/api/dashboard/twilio-credentials", {
        method: "PATCH",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          organizationId,
          twilioAccountSid: accountSid.trim(),
          twilioAuthToken: authToken.trim(),
          twilioWhatsappNumber: whatsappNumber.trim(),
        }),
      });

      const data = await res.json();
      if (!res.ok || data.success === false) {
        setError(data.error || (isAr ? "فشل الحفظ" : "Save failed"));
        return;
      }

      onSuccess({ displayNumber: whatsappNumber.trim() });
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "خطأ غير متوقع"
            : "Unexpected error",
      );
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div
        dir={dir}
        className="rounded-xl bg-white shadow-sm p-12 flex items-center justify-center text-slate-500"
      >
        <Loader2 className="w-5 h-5 animate-spin mr-2" />
        {t.loadingOrg}
      </div>
    );
  }

  return (
    <div className="rounded-xl bg-white shadow-sm p-8" dir={dir}>
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold text-slate-900 mb-2">{t.title}</h2>
          <p className="text-slate-600">{t.subtitle}</p>
        </div>

        {/* Webhook URL panel — show prominently so they can copy it */}
        {server?.webhookUrl && (
          <div className="mb-8 rounded-2xl border-2 border-emerald-200 bg-gradient-to-br from-emerald-50 to-green-50 p-5">
            <div className="flex items-start justify-between gap-3 mb-3">
              <div>
                <h3 className="text-base font-semibold text-emerald-900 mb-1">
                  {t.webhookSection}
                </h3>
                <p className="text-xs text-emerald-700">{t.webhookHelp}</p>
              </div>
              <a
                href="https://console.twilio.com/us1/develop/sms/try-it-out/whatsapp-learn"
                target="_blank"
                rel="noopener noreferrer"
                className="flex-shrink-0 inline-flex items-center gap-1 text-xs font-medium text-emerald-700 hover:text-emerald-900"
              >
                <ExternalLink className="w-3 h-3" />
                {t.openTwilio}
              </a>
            </div>
            <div className="flex items-center gap-2 bg-white rounded-lg border border-emerald-200 px-3 py-2">
              <code
                className="flex-1 text-xs font-mono text-slate-700 truncate"
                dir="ltr"
              >
                {server.webhookUrl}
              </code>
              <button
                type="button"
                onClick={handleCopyWebhook}
                className="flex-shrink-0 inline-flex items-center gap-1 text-xs font-medium text-emerald-700 hover:text-emerald-900 px-2 py-1 rounded"
              >
                {copied ? (
                  <>
                    <Check className="w-3 h-3" />
                    {t.copied}
                  </>
                ) : (
                  <>
                    <Copy className="w-3 h-3" />
                    {t.copy}
                  </>
                )}
              </button>
            </div>
            <p className="text-xs text-emerald-700 mt-2">{t.methodPost}</p>
          </div>
        )}

        {/* Credentials form */}
        <div className="space-y-5">
          {/* Account SID */}
          <div>
            <label className="block text-sm font-medium text-slate-900 mb-1.5">
              {t.accountSidLabel}
            </label>
            <input
              type="text"
              value={accountSid}
              onChange={(e) => setAccountSid(e.target.value)}
              placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
              dir="ltr"
              className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm font-mono placeholder-slate-400 focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 focus:outline-none transition-all"
            />
            <p className="text-xs text-slate-500 mt-1">{t.accountSidHelp}</p>
          </div>

          {/* Auth Token */}
          <div>
            <label className="block text-sm font-medium text-slate-900 mb-1.5">
              {t.authTokenLabel}
            </label>
            <input
              type="password"
              value={authToken}
              onChange={(e) => setAuthToken(e.target.value)}
              placeholder={
                server?.twilioAuthTokenMasked || "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
              }
              dir="ltr"
              autoComplete="off"
              className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm font-mono placeholder-slate-400 focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 focus:outline-none transition-all"
            />
            <p className="text-xs text-slate-500 mt-1">{t.authTokenHelp}</p>
          </div>

          {/* WhatsApp Number */}
          <div>
            <label className="block text-sm font-medium text-slate-900 mb-1.5">
              {t.whatsappNumberLabel}
            </label>
            <input
              type="text"
              value={whatsappNumber}
              onChange={(e) => setWhatsappNumber(e.target.value)}
              placeholder="+14155238886"
              dir="ltr"
              className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm font-mono placeholder-slate-400 focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 focus:outline-none transition-all"
            />
            <p className="text-xs text-slate-500 mt-1">{t.whatsappNumberHelp}</p>
            <p className="text-xs text-emerald-600 mt-1">{t.sandboxHint}</p>
          </div>

          {/* Error */}
          {error && (
            <div className="flex items-start gap-2 rounded-xl bg-rose-50 border border-rose-200 px-4 py-3">
              <AlertCircle className="w-4 h-4 text-rose-600 flex-shrink-0 mt-0.5" />
              <span className="text-sm text-rose-700">{error}</span>
            </div>
          )}
        </div>

        {/* Actions */}
        <div
          className={`mt-8 flex items-center justify-between ${isAr ? "flex-row-reverse" : ""}`}
        >
          <button
            type="button"
            onClick={onBack}
            disabled={saving}
            className={`flex items-center gap-2 px-5 py-2.5 text-slate-600 hover:text-slate-900 font-medium transition-colors disabled:opacity-50 ${isAr ? "flex-row-reverse" : ""}`}
          >
            {isAr ? (
              <ChevronRight className="w-4 h-4" />
            ) : (
              <ChevronLeft className="w-4 h-4" />
            )}
            {t.back}
          </button>

          <button
            type="button"
            onClick={handleSave}
            disabled={saving || !organizationId}
            className="inline-flex items-center gap-2 px-6 py-2.5 bg-emerald-600 text-white font-semibold rounded-xl hover:bg-emerald-700 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {saving && <Loader2 className="w-4 h-4 animate-spin" />}
            {saving ? t.saving : t.save}
          </button>
        </div>
      </div>
    </div>
  );
}
