/**
 * WhatsApp Credentials Form
 * Simplified credential entry for the onboarding wizard
 */

"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Key,
  Eye,
  EyeOff,
  CheckCircle,
  AlertCircle,
  Loader2,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

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

interface ValidationResult {
  valid: boolean;
  displayNumber?: string;
  businessName?: string;
  error?: string;
}

export default function WhatsAppCredentialsForm({
  lang,
  onSuccess,
  onBack,
}: WhatsAppCredentialsFormProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";
  const dt = isAr ? dashboardAr : dashboardEn;

  // Use existing translations from OrgWhatsAppKeysForm pattern
  const t = {
    phoneNumberId: isAr ? "معرف رقم الهاتف" : "Phone Number ID",
    accessToken: isAr ? "رمز الوصول" : "Access Token",
    appSecret: isAr ? "سر التطبيق" : "App Secret",
    phoneNumberIdHint: isAr
      ? "معرف رقم الهاتف من Meta Business Suite (أرقام فقط)"
      : "Phone Number ID from Meta Business Suite (numbers only)",
    accessTokenHint: isAr
      ? "رمز الوصول الدائم من تطبيق Meta الخاص بك (يبدأ بـ EAA)"
      : "Permanent Access Token from your Meta App (starts with EAA)",
    appSecretHint: isAr
      ? "سر التطبيق للتحقق من توقيع Webhook (سداسي عشري)"
      : "App Secret for webhook signature verification (hexadecimal)",
    validateKeys: isAr ? "التحقق من المفاتيح" : "Validate Keys",
    validating: isAr ? "جاري التحقق..." : "Validating...",
    saveKeys: isAr ? "حفظ المفاتيح" : "Save Keys",
    saving: isAr ? "جاري الحفظ..." : "Saving...",
    keysValid: isAr ? "المفاتيح صالحة" : "Keys Valid",
    validationFailed: isAr ? "فشل التحقق" : "Validation Failed",
    keysRequired: isAr ? "جميع الحقول مطلوبة" : "All fields are required",
    invalidPhoneNumberId: isAr
      ? "معرف رقم الهاتف يجب أن يكون أرقامًا فقط"
      : "Phone Number ID must be numbers only",
    invalidAccessToken: isAr
      ? "رمز الوصول يجب أن يبدأ بـ EAA"
      : "Access Token must start with EAA",
    invalidAppSecret: isAr
      ? "سر التطبيق يجب أن يكون سداسي عشري"
      : "App Secret must be hexadecimal",
    pleaseValidateFirst: isAr
      ? "يرجى التحقق من المفاتيح أولاً"
      : "Please validate keys first",
    displayNumber: isAr ? "رقم العرض" : "Display Number",
    businessName: isAr ? "اسم النشاط التجاري" : "Business Name",
  };

  // Form state
  const [phoneNumberId, setPhoneNumberId] = useState("");
  const [accessToken, setAccessToken] = useState("");
  const [appSecret, setAppSecret] = useState("");

  // Visibility toggles
  const [showAccessToken, setShowAccessToken] = useState(false);
  const [showAppSecret, setShowAppSecret] = useState(false);

  // State
  const [validating, setValidating] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [validationResult, setValidationResult] =
    useState<ValidationResult | null>(null);
  const [isValidated, setIsValidated] = useState(false);

  const handleValidate = async () => {
    setError(null);
    setValidationResult(null);
    setIsValidated(false);

    // Basic validation
    if (!phoneNumberId.trim() || !accessToken.trim() || !appSecret.trim()) {
      setError(t.keysRequired);
      return;
    }

    if (!/^\d+$/.test(phoneNumberId)) {
      setError(t.invalidPhoneNumberId);
      return;
    }

    if (!accessToken.startsWith("EAA")) {
      setError(t.invalidAccessToken);
      return;
    }

    if (!/^[a-f0-9]+$/i.test(appSecret)) {
      setError(t.invalidAppSecret);
      return;
    }

    try {
      setValidating(true);
      const response = await fetchWithCSRF(
        "/api/settings/whatsapp-keys/validate",
        {
          method: "POST",
          body: JSON.stringify({
            phoneNumberId: phoneNumberId.trim(),
            accessToken: accessToken.trim(),
          }),
        },
      );

      const data = await response.json();

      if (response.ok && data.valid) {
        setValidationResult({
          valid: true,
          displayNumber: data.displayNumber,
          businessName: data.businessName,
        });
        setIsValidated(true);
        setError(null); // Clear any previous errors
      } else {
        // Only use validationResult for API validation results, not error state
        setValidationResult({
          valid: false,
          error: data.error || t.validationFailed,
        });
        setIsValidated(false);
        // Don't set error separately - validationResult handles it
      }
    } catch (err) {
      // Network/other errors go in error state, not validationResult
      setError(err instanceof Error ? err.message : "Network error");
      setValidationResult(null);
    } finally {
      setValidating(false);
    }
  };

  const handleSave = async () => {
    if (!isValidated) {
      setError(t.pleaseValidateFirst);
      return;
    }

    try {
      setSaving(true);
      setError(null);

      const response = await fetchWithCSRF("/api/settings/whatsapp-keys", {
        method: "POST",
        body: JSON.stringify({
          phoneNumberId: phoneNumberId.trim(),
          accessToken: accessToken.trim(),
          appSecret: appSecret.trim(),
        }),
      });

      const data = await response.json();

      if (response.ok) {
        onSuccess({
          displayNumber: validationResult?.displayNumber,
          businessName: validationResult?.businessName,
        });
      } else {
        setError(data.error || "Failed to save credentials");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Network error");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="rounded-xl bg-white p-6 shadow-sm" dir={dir}>
      <div className="mx-auto max-w-xl">
        {/* Header */}
        <div
          className={`mb-6 flex items-center gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-green-100">
            <Key className="h-5 w-5 text-green-600" />
          </div>
          <div className={isAr ? "text-right" : ""}>
            <h3 className="text-lg font-bold text-slate-900">
              {dt.whatsappSetupTitle}
            </h3>
            <p className="text-sm text-slate-500">{dt.whatsappSetupSubtitle}</p>
          </div>
        </div>

        {/* Form Fields */}
        <div className="space-y-5">
          {/* Phone Number ID */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {t.phoneNumberId} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={phoneNumberId}
              onChange={(e) => {
                setPhoneNumberId(e.target.value.replace(/\D/g, ""));
                setValidationResult(null);
                setIsValidated(false);
              }}
              placeholder="123456789012345"
              className="w-full rounded-xl border-2 border-slate-200 px-4 py-2.5 transition-colors focus:border-green-500 focus:ring-2 focus:ring-green-500"
              dir="ltr"
            />
            <p className="mt-1 text-xs text-slate-500">{t.phoneNumberIdHint}</p>
          </div>

          {/* Access Token */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {t.accessToken} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showAccessToken ? "text" : "password"}
                value={accessToken}
                onChange={(e) => {
                  setAccessToken(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="EAAxxxxxxxxxx..."
                className={`w-full rounded-xl border-2 border-slate-200 px-4 py-2.5 ${isAr ? "pl-12" : "pr-12"} transition-colors focus:border-green-500 focus:ring-2 focus:ring-green-500`}
                dir="ltr"
              />
              <button
                type="button"
                onClick={() => setShowAccessToken(!showAccessToken)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showAccessToken ? (
                  <EyeOff className="h-5 w-5" />
                ) : (
                  <Eye className="h-5 w-5" />
                )}
              </button>
            </div>
            <p className="mt-1 text-xs text-slate-500">{t.accessTokenHint}</p>
          </div>

          {/* App Secret */}
          <div>
            <label className="mb-2 block text-sm font-medium text-slate-700">
              {t.appSecret} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showAppSecret ? "text" : "password"}
                value={appSecret}
                onChange={(e) => {
                  setAppSecret(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="abc123def456..."
                className={`w-full rounded-xl border-2 border-slate-200 px-4 py-2.5 ${isAr ? "pl-12" : "pr-12"} transition-colors focus:border-green-500 focus:ring-2 focus:ring-green-500`}
                dir="ltr"
              />
              <button
                type="button"
                onClick={() => setShowAppSecret(!showAppSecret)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showAppSecret ? (
                  <EyeOff className="h-5 w-5" />
                ) : (
                  <Eye className="h-5 w-5" />
                )}
              </button>
            </div>
            <p className="mt-1 text-xs text-slate-500">{t.appSecretHint}</p>
          </div>

          {/* Validation Result */}
          {validationResult && (
            <div
              className={`rounded-xl border-2 p-4 ${
                validationResult.valid
                  ? "border-green-200 bg-green-50"
                  : "border-red-200 bg-red-50"
              }`}
            >
              <div
                className={`flex items-start gap-3 ${isAr ? "flex-row-reverse" : ""}`}
              >
                {validationResult.valid ? (
                  <CheckCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-green-600" />
                ) : (
                  <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-red-600" />
                )}
                <div className="flex-1">
                  <p
                    className={`font-semibold ${validationResult.valid ? "text-green-900" : "text-red-900"}`}
                  >
                    {validationResult.valid ? t.keysValid : t.validationFailed}
                  </p>
                  {validationResult.valid ? (
                    <div className="mt-2 space-y-1 text-sm text-green-800">
                      {validationResult.displayNumber && (
                        <p>
                          <strong>{t.displayNumber}:</strong>{" "}
                          {validationResult.displayNumber}
                        </p>
                      )}
                      {validationResult.businessName && (
                        <p>
                          <strong>{t.businessName}:</strong>{" "}
                          {validationResult.businessName}
                        </p>
                      )}
                    </div>
                  ) : (
                    validationResult.error && (
                      <p className="mt-2 text-sm text-red-800">
                        {validationResult.error}
                      </p>
                    )
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Error Display */}
          {error && (
            <div className="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700">
              {error}
            </div>
          )}

          {/* Action Buttons */}
          <div
            className={`flex items-center gap-3 pt-4 ${isAr ? "flex-row-reverse" : ""}`}
          >
            <button
              onClick={handleValidate}
              disabled={
                validating ||
                !phoneNumberId.trim() ||
                !accessToken.trim() ||
                !appSecret.trim()
              }
              className={`flex items-center gap-2 rounded-xl bg-blue-600 px-5 py-2.5 font-semibold text-white transition-all hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50 ${isAr ? "flex-row-reverse" : ""}`}
            >
              {validating ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Key className="h-4 w-4" />
              )}
              {validating ? t.validating : t.validateKeys}
            </button>

            <button
              onClick={handleSave}
              disabled={saving || !isValidated}
              className={`flex items-center gap-2 rounded-xl bg-green-600 px-5 py-2.5 font-semibold text-white transition-all hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-50 ${isAr ? "flex-row-reverse" : ""}`}
            >
              {saving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <CheckCircle className="h-4 w-4" />
              )}
              {saving ? t.saving : t.saveKeys}
            </button>
          </div>
        </div>

        {/* Back Button */}
        <div
          className={`mt-6 border-t border-slate-200 pt-6 ${isAr ? "text-right" : ""}`}
        >
          <button
            onClick={onBack}
            className={`flex items-center gap-2 font-medium text-slate-600 transition-colors hover:text-slate-900 ${isAr ? "flex-row-reverse" : ""}`}
          >
            {isAr ? (
              <ChevronRight className="h-4 w-4" />
            ) : (
              <ChevronLeft className="h-4 w-4" />
            )}
            {dt.whatsappSetupPrevious}
          </button>
        </div>
      </div>
    </div>
  );
}
