/**
 * WhatsApp Setup Step - Connect WhatsApp Business
 *
 * Primary: Meta Embedded Signup (one-click OAuth via Facebook Login for Business)
 * Fallback: Manual credential entry (phone_number_id + access_token)
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import {
  MessageSquare,
  CheckCircle2,
  XCircle,
  Loader2,
  ChevronDown,
  ChevronUp,
  Shield,
  Phone,
  Key,
  Lock,
  RefreshCw,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type { WhatsAppMethod } from "@/lib/types/onboarding.types";

// ── Facebook SDK type augmentation ──────────────────────────────────────────
declare global {
  interface Window {
    FB?: {
      init: (params: {
        appId: string;
        cookie: boolean;
        xfbml: boolean;
        version: string;
      }) => void;
      login: (
        callback: (response: {
          authResponse?: { code?: string; accessToken?: string };
          status?: string;
        }) => void,
        params: Record<string, unknown>,
      ) => void;
    };
    fbAsyncInit?: () => void;
  }
}

// ── Constants ───────────────────────────────────────────────────────────────
const META_APP_ID = process.env.NEXT_PUBLIC_META_APP_ID || "";
const META_CONFIG_ID = process.env.NEXT_PUBLIC_META_CONFIG_ID || "";
const FB_SDK_VERSION = "v19.0";

type ConnectionStep = "connect" | "verifying" | "done";
type ConnectionStatus = "idle" | "loading" | "success" | "error";

interface WhatsAppSetupStepProps {
  lang: Lang;
  onContinue: (method: WhatsAppMethod) => void;
  onSkip: () => void;
}

export default function WhatsAppSetupStep({
  lang,
  onContinue,
  onSkip,
}: WhatsAppSetupStepProps) {
  const isAr = lang === "ar";

  // ── State ───────────────────────────────────────────────────────────────
  const [currentStep, setCurrentStep] = useState<ConnectionStep>("connect");
  const [connectionStatus, setConnectionStatus] =
    useState<ConnectionStatus>("idle");
  const [errorMessage, setErrorMessage] = useState("");
  const [connectedNumber, setConnectedNumber] = useState("");
  const [sdkReady, setSdkReady] = useState(false);
  const [showManual, setShowManual] = useState(false);

  // Manual form fields
  const [manualPhoneId, setManualPhoneId] = useState("");
  const [manualToken, setManualToken] = useState("");
  const [manualConnecting, setManualConnecting] = useState(false);

  // ── Translations ────────────────────────────────────────────────────────
  const t = {
    title: isAr ? "اربط حساب واتساب بيزنس" : "Connect WhatsApp Business",
    subtitle: isAr
      ? "اربط حسابك في خطوة وحدة عبر ميتا"
      : "Connect your account in one step via Meta",

    // Step indicators
    step1: isAr ? "ربط" : "Connect",
    step2: isAr ? "تحقق" : "Verify",
    step3: isAr ? "جاهز" : "Done",

    // Primary method
    connectBtn: isAr ? "ربط حساب واتساب" : "Connect with WhatsApp",
    connectDesc: isAr
      ? "ربط آمن بضغطة وحدة عبر ميتا بيزنس"
      : "Secure one-click connection via Meta Business",
    connecting: isAr ? "جارٍ الربط..." : "Connecting...",
    verifying: isAr ? "جارٍ التحقق..." : "Verifying connection...",
    connected: isAr ? "تم الربط بنجاح!" : "Connected successfully!",
    connectedNumber: isAr ? "الرقم المتصل:" : "Connected number:",

    // Errors
    errorGeneric: isAr
      ? "فشل الربط. حاول مرة أخرى."
      : "Connection failed. Please try again.",
    errorCancelled: isAr
      ? "تم إلغاء الربط. حاول مرة أخرى."
      : "Connection was cancelled. Please try again.",
    errorSdk: isAr
      ? "خطأ في تحميل الخدمة. حاول مرة أخرى."
      : "Failed to load service. Please try again.",
    retry: isAr ? "حاول مرة أخرى" : "Try Again",

    // Manual fallback
    manualTitle: isAr
      ? "متقدم: أدخل البيانات يدوياً"
      : "Advanced: Enter credentials manually",
    manualDesc: isAr
      ? "إذا عندك بيانات واتساب بيزنس API"
      : "If you have WhatsApp Business API credentials",
    phoneIdLabel: isAr ? "معرّف رقم الهاتف" : "Phone Number ID",
    phoneIdPlaceholder: isAr ? "أدخل معرّف رقم الهاتف" : "Enter Phone Number ID",
    tokenLabel: isAr ? "رمز الوصول" : "Access Token",
    tokenPlaceholder: isAr ? "أدخل رمز الوصول" : "Enter Access Token",
    manualConnectBtn: isAr ? "ربط يدوي" : "Connect Manually",

    // Skip / continue
    skipBtn: isAr ? "تخطي الآن" : "Skip for now",
    skipInfo: isAr
      ? "يمكنك ربط واتساب لاحقاً من الإعدادات"
      : "You can connect WhatsApp later from settings",
    continueBtn: isAr ? "متابعة" : "Continue",

    // Security note
    securityNote: isAr
      ? "بياناتك محمية بتشفير AES-256"
      : "Your data is protected with AES-256 encryption",
  };

  // ── Load Facebook SDK ─────────────────────────────────────────────────
  useEffect(() => {
    if (!META_APP_ID) {
      // No app ID configured — skip SDK loading
      return;
    }

    // Avoid loading if already present
    if (window.FB) {
      setSdkReady(true);
      return;
    }

    const existingScript = document.getElementById("facebook-jssdk");
    if (existingScript) {
      // Script tag exists, wait for initialization
      const checkFB = setInterval(() => {
        if (window.FB) {
          setSdkReady(true);
          clearInterval(checkFB);
        }
      }, 200);
      const timeout = setTimeout(() => clearInterval(checkFB), 10000);
      return () => {
        clearInterval(checkFB);
        clearTimeout(timeout);
      };
    }

    // Define the async init callback before appending the script
    window.fbAsyncInit = () => {
      window.FB?.init({
        appId: META_APP_ID,
        cookie: true,
        xfbml: true,
        version: FB_SDK_VERSION,
      });
      setSdkReady(true);
    };

    const script = document.createElement("script");
    script.id = "facebook-jssdk";
    script.src = "https://connect.facebook.net/en_US/sdk.js";
    script.async = true;
    script.defer = true;
    script.crossOrigin = "anonymous";
    document.body.appendChild(script);

    // Cleanup is intentionally omitted: the FB SDK should persist for the
    // lifetime of the page since other components may also use it.
  }, []);

  // ── Exchange OAuth code with backend ──────────────────────────────────
  const exchangeCode = useCallback(
    async (code: string, state: string) => {
      setCurrentStep("verifying");
      setConnectionStatus("loading");
      setErrorMessage("");

      try {
        const response = await fetch(
          "/api/integrations/whatsapp/oauth/callback",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            credentials: "include",
            body: JSON.stringify({ code, state }),
          },
        );

        const data = await response.json();

        if (response.ok && data.success) {
          setConnectionStatus("success");
          setCurrentStep("done");
          const phone = data.data?.phoneNumber || data.phoneNumber;
          if (phone) {
            setConnectedNumber(phone);
          }
          // Auto-continue after a short delay so the user sees the success state
          setTimeout(() => {
            onContinue("meta_api");
          }, 2000);
        } else {
          setConnectionStatus("error");
          setErrorMessage(data.error || t.errorGeneric);
          setCurrentStep("connect");
        }
      } catch {
        setConnectionStatus("error");
        setErrorMessage(t.errorGeneric);
        setCurrentStep("connect");
      }
    },
    [onContinue, t.errorGeneric],
  );

  // ── Launch Embedded Signup ────────────────────────────────────────────
  const handleEmbeddedSignup = useCallback(async () => {
    if (!window.FB) {
      setConnectionStatus("error");
      setErrorMessage(t.errorSdk);
      return;
    }

    setConnectionStatus("loading");
    setErrorMessage("");

    // 1. Fetch a CSRF state token from our backend. The backend sets an
    //    HttpOnly cookie with the same value and returns it here so we can
    //    round-trip it through the OAuth flow and prove to the callback
    //    that this exchange originated from our UI.
    let state: string;
    try {
      const stateRes = await fetch(
        "/api/integrations/whatsapp/oauth/state",
        { credentials: "include" },
      );
      if (!stateRes.ok) {
        setConnectionStatus("error");
        setErrorMessage(t.errorGeneric);
        return;
      }
      const stateData = await stateRes.json();
      if (!stateData?.state) {
        setConnectionStatus("error");
        setErrorMessage(t.errorGeneric);
        return;
      }
      state = stateData.state;
    } catch {
      setConnectionStatus("error");
      setErrorMessage(t.errorGeneric);
      return;
    }

    // 2. Launch the Meta Embedded Signup popup, passing the state through
    //    so the callback can validate it against the cookie.
    window.FB.login(
      (response) => {
        if (response.authResponse?.code) {
          exchangeCode(response.authResponse.code, state);
        } else {
          setConnectionStatus("error");
          setErrorMessage(t.errorCancelled);
        }
      },
      {
        config_id: META_CONFIG_ID,
        response_type: "code",
        override_default_response_type: true,
        extras: {
          setup: {},
          featureType: "",
          sessionInfoVersion: "2",
          state,
        },
      },
    );
  }, [exchangeCode, t.errorSdk, t.errorCancelled, t.errorGeneric]);

  // ── Manual connect handler ────────────────────────────────────────────
  const handleManualConnect = async () => {
    if (!manualPhoneId.trim() || !manualToken.trim()) return;

    setManualConnecting(true);
    setErrorMessage("");

    try {
      const response = await fetch("/api/integrations/whatsapp/connect", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          phone_number_id: manualPhoneId.trim(),
          access_token: manualToken.trim(),
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setConnectionStatus("success");
        setCurrentStep("done");
        setConnectedNumber(manualPhoneId.trim());
        setTimeout(() => {
          onContinue("meta_api");
        }, 2000);
      } else {
        setConnectionStatus("error");
        setErrorMessage(data.error || t.errorGeneric);
      }
    } catch {
      setConnectionStatus("error");
      setErrorMessage(t.errorGeneric);
    } finally {
      setManualConnecting(false);
    }
  };

  // ── Skip handler ─────────────────────────────────────────────────────
  const handleSkip = () => {
    onSkip();
    onContinue("skipped");
  };

  // ── Reset / retry ─────────────────────────────────────────────────────
  const handleRetry = () => {
    setConnectionStatus("idle");
    setErrorMessage("");
    setCurrentStep("connect");
  };

  // ── Step indicator ────────────────────────────────────────────────────
  const steps = [
    { key: "connect" as const, label: t.step1 },
    { key: "verifying" as const, label: t.step2 },
    { key: "done" as const, label: t.step3 },
  ];
  const stepIndex = steps.findIndex((s) => s.key === currentStep);

  return (
    <div className="space-y-8 animate-fadeIn">
      {/* Header */}
      <div className="text-center">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-green-500 to-emerald-600 shadow-lg shadow-green-500/25 mb-6">
          <MessageSquare className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-3xl font-bold text-slate-900 mb-3">{t.title}</h2>
        <p className="text-lg text-slate-600">{t.subtitle}</p>
      </div>

      {/* Step Indicator */}
      <div className="flex items-center justify-center gap-2">
        {steps.map((step, idx) => (
          <div key={step.key} className="flex items-center gap-2">
            <div
              className={`flex items-center justify-center w-8 h-8 rounded-full text-sm font-bold transition-all ${
                idx <= stepIndex
                  ? "bg-green-500 text-white shadow-md shadow-green-500/30"
                  : "bg-slate-200 text-slate-500"
              }`}
            >
              {idx < stepIndex ? (
                <CheckCircle2 className="w-5 h-5" />
              ) : (
                idx + 1
              )}
            </div>
            <span
              className={`text-sm font-medium ${
                idx <= stepIndex ? "text-green-700" : "text-slate-400"
              }`}
            >
              {step.label}
            </span>
            {idx < steps.length - 1 && (
              <div
                className={`w-8 h-0.5 mx-1 transition-colors ${
                  idx < stepIndex ? "bg-green-500" : "bg-slate-200"
                }`}
              />
            )}
          </div>
        ))}
      </div>

      {/* ── Primary: Embedded Signup Card ────────────────────────────────── */}
      {currentStep === "connect" && (
        <div className="p-6 rounded-2xl bg-white border-2 border-slate-200 space-y-5">
          {/* WhatsApp Connect Button */}
          <div className="text-center space-y-4">
            <button
              onClick={handleEmbeddedSignup}
              disabled={
                connectionStatus === "loading" ||
                connectionStatus === "success" ||
                (!sdkReady && !!META_APP_ID)
              }
              className="inline-flex items-center gap-3 px-8 py-4 rounded-xl text-white font-bold text-lg shadow-lg hover:shadow-xl disabled:opacity-60 disabled:cursor-not-allowed transition-all hover:-translate-y-0.5 active:translate-y-0"
              style={{ backgroundColor: "#25D366" }}
            >
              {connectionStatus === "loading" ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  {t.connecting}
                </>
              ) : (
                <>
                  {/* WhatsApp SVG icon */}
                  <svg
                    className="w-6 h-6"
                    viewBox="0 0 24 24"
                    fill="currentColor"
                  >
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                  </svg>
                  {t.connectBtn}
                </>
              )}
            </button>

            <p className="text-sm text-slate-500 flex items-center justify-center gap-1.5">
              <Shield className="w-4 h-4 text-green-600" />
              {t.connectDesc}
            </p>
          </div>
        </div>
      )}

      {/* ── Verifying State ──────────────────────────────────────────────── */}
      {currentStep === "verifying" && (
        <div className="p-8 rounded-2xl bg-white border-2 border-green-200 text-center space-y-4">
          <Loader2 className="w-10 h-10 text-green-500 animate-spin mx-auto" />
          <p className="text-lg font-semibold text-slate-700">{t.verifying}</p>
        </div>
      )}

      {/* ── Success State ────────────────────────────────────────────────── */}
      {currentStep === "done" && connectionStatus === "success" && (
        <div className="p-8 rounded-2xl bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-300 text-center space-y-4">
          <CheckCircle2 className="w-12 h-12 text-green-500 mx-auto" />
          <p className="text-xl font-bold text-green-800">{t.connected}</p>
          {connectedNumber && (
            <p className="text-sm text-green-700">
              {t.connectedNumber}{" "}
              <span className="font-mono font-bold">{connectedNumber}</span>
            </p>
          )}
        </div>
      )}

      {/* ── Error Message ────────────────────────────────────────────────── */}
      {connectionStatus === "error" && errorMessage && (
        <div className="p-4 rounded-xl bg-red-50 border border-red-200 flex items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <XCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
            <p className="text-sm text-red-700">{errorMessage}</p>
          </div>
          <button
            onClick={handleRetry}
            className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium text-red-700 bg-red-100 hover:bg-red-200 transition-colors flex-shrink-0"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            {t.retry}
          </button>
        </div>
      )}

      {/* ── Manual Credentials Fallback ──────────────────────────────────── */}
      {currentStep === "connect" && (
        <div className="rounded-2xl border border-slate-200 overflow-hidden">
          {/* Collapsible header */}
          <button
            onClick={() => setShowManual(!showManual)}
            className="w-full flex items-center justify-between p-4 text-left hover:bg-slate-50 transition-colors"
          >
            <div className="flex items-center gap-2">
              <Key className="w-4 h-4 text-slate-400" />
              <span className="text-sm font-medium text-slate-600">
                {t.manualTitle}
              </span>
            </div>
            {showManual ? (
              <ChevronUp className="w-4 h-4 text-slate-400" />
            ) : (
              <ChevronDown className="w-4 h-4 text-slate-400" />
            )}
          </button>

          {/* Collapsible content */}
          {showManual && (
            <div className="px-4 pb-5 space-y-4 border-t border-slate-100">
              <p className="text-xs text-slate-500 pt-3">{t.manualDesc}</p>

              {/* Phone Number ID */}
              <div>
                <label className="flex items-center gap-1.5 text-sm font-medium text-slate-700 mb-1.5">
                  <Phone className="w-3.5 h-3.5" />
                  {t.phoneIdLabel}
                </label>
                <input
                  type="text"
                  value={manualPhoneId}
                  onChange={(e) => setManualPhoneId(e.target.value)}
                  placeholder={t.phoneIdPlaceholder}
                  className="w-full px-4 py-2.5 rounded-lg border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent placeholder:text-slate-400"
                  dir="ltr"
                />
              </div>

              {/* Access Token */}
              <div>
                <label className="flex items-center gap-1.5 text-sm font-medium text-slate-700 mb-1.5">
                  <Lock className="w-3.5 h-3.5" />
                  {t.tokenLabel}
                </label>
                <input
                  type="password"
                  value={manualToken}
                  onChange={(e) => setManualToken(e.target.value)}
                  placeholder={t.tokenPlaceholder}
                  className="w-full px-4 py-2.5 rounded-lg border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent placeholder:text-slate-400"
                  dir="ltr"
                />
              </div>

              {/* Manual connect button */}
              <button
                onClick={handleManualConnect}
                disabled={
                  manualConnecting ||
                  !manualPhoneId.trim() ||
                  !manualToken.trim()
                }
                className="w-full inline-flex items-center justify-center gap-2 px-6 py-3 rounded-xl border-2 border-green-500 text-green-700 font-semibold hover:bg-green-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
              >
                {manualConnecting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {t.connecting}
                  </>
                ) : (
                  t.manualConnectBtn
                )}
              </button>
            </div>
          )}
        </div>
      )}

      {/* ── Security note ────────────────────────────────────────────────── */}
      {currentStep === "connect" && (
        <p className="text-xs text-center text-slate-400 flex items-center justify-center gap-1">
          <Shield className="w-3 h-3" />
          {t.securityNote}
        </p>
      )}

      {/* ── Skip Option ──────────────────────────────────────────────────── */}
      {currentStep !== "done" && (
        <div className="text-center space-y-3">
          <p className="text-sm text-slate-500">{t.skipInfo}</p>
          <button
            onClick={handleSkip}
            disabled={connectionStatus === "loading"}
            className="text-sm font-medium text-slate-600 hover:text-green-600 transition-colors disabled:opacity-50"
          >
            {t.skipBtn}
          </button>
        </div>
      )}

      {/* ── Continue Button (after success) ──────────────────────────────── */}
      {currentStep === "done" && connectionStatus === "success" && (
        <div className="flex justify-center pt-4">
          <button
            onClick={() => onContinue("meta_api")}
            className="inline-flex items-center gap-2 px-8 py-4 rounded-xl bg-gradient-to-r from-green-500 to-emerald-600 text-white font-semibold shadow-lg shadow-green-500/25 hover:shadow-green-500/40 hover:-translate-y-0.5 transition-all"
          >
            {t.continueBtn}
            <span className="text-xl">{isAr ? "\u2190" : "\u2192"}</span>
          </button>
        </div>
      )}

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: 0.4s ease-out forwards fadeIn;
        }
      `}</style>
    </div>
  );
}
