"use client";

import { useState, useCallback, useEffect, FormEvent } from "react";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
import { Loader2, CheckCircle, AlertCircle } from "lucide-react";

function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? decodeURIComponent(match[1]) : null;
}

interface PartnerSignupFormProps {
  isAr: boolean;
}

const COMPANY_TYPES_EN = [
  "IT Provider",
  "Business Consultant",
  "Medical Equipment",
  "Marketing Agency",
  "Other",
];
const COMPANY_TYPES_AR = [
  "مزود تكنولوجيا المعلومات",
  "مستشار أعمال",
  "معدات طبية",
  "وكالة تسويق",
  "أخرى",
];

const GCC_COUNTRIES_EN = [
  "Qatar",
  "Saudi Arabia",
  "United Arab Emirates",
  "Kuwait",
  "Bahrain",
  "Oman",
];
const GCC_COUNTRIES_AR = [
  "قطر",
  "المملكة العربية السعودية",
  "الإمارات العربية المتحدة",
  "الكويت",
  "البحرين",
  "عُمان",
];

export default function PartnerSignupForm({ isAr }: PartnerSignupFormProps) {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [company, setCompany] = useState("");
  const [companyType, setCompanyType] = useState("");
  const [website, setWebsite] = useState("");
  const [country, setCountry] = useState("");

  useEffect(() => {
    fetch("/api/csrf").catch(() => {});
  }, []);

  const handleSubmit = useCallback(
    async (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setError(null);

      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!email.trim() || !emailRegex.test(email)) {
        setError(
          isAr
            ? "يرجى إدخال بريد إلكتروني صالح."
            : "Please enter a valid email address.",
        );
        return;
      }
      if (!name.trim() || !phone.trim() || !company.trim()) {
        setError(
          isAr
            ? "يرجى تعبئة جميع الحقول المطلوبة."
            : "Please fill in all required fields.",
        );
        return;
      }
      if (!companyType || !country) {
        setError(
          isAr
            ? "يرجى اختيار نوع الشركة والدولة."
            : "Please select company type and country.",
        );
        return;
      }

      setIsSubmitting(true);

      try {
        let recaptchaToken = "";
        if (executeRecaptcha) {
          recaptchaToken = await executeRecaptcha("partner_signup");
        }

        const csrfToken = getCSRFToken();
        const response = await fetch("/api/partners", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(csrfToken && { "x-csrf-token": csrfToken }),
          },
          body: JSON.stringify({
            name: name.trim(),
            email: email.trim(),
            phone: phone.trim(),
            company: company.trim(),
            companyType,
            website: website.trim() || undefined,
            country,
            recaptchaToken,
          }),
        });

        if (!response.ok) {
          const data = await response.json();
          throw new Error(
            data.error ||
              (isAr
                ? "حدث خطأ. يرجى المحاولة مرة أخرى."
                : "Submission failed. Please try again."),
          );
        }

        setSuccess(true);
        setName("");
        setEmail("");
        setPhone("");
        setCompany("");
        setCompanyType("");
        setWebsite("");
        setCountry("");
      } catch (err) {
        console.error("Partner signup error:", err);
        setError(
          err instanceof Error
            ? err.message
            : isAr
              ? "حدث خطأ. يرجى المحاولة مرة أخرى."
              : "Something went wrong. Please try again.",
        );
      } finally {
        setIsSubmitting(false);
      }
    },
    [
      name,
      email,
      phone,
      company,
      companyType,
      website,
      country,
      executeRecaptcha,
      isAr,
    ],
  );

  const companyTypes = isAr ? COMPANY_TYPES_AR : COMPANY_TYPES_EN;
  const companyTypeValues = COMPANY_TYPES_EN;
  const countries = isAr ? GCC_COUNTRIES_AR : GCC_COUNTRIES_EN;
  const countryValues = GCC_COUNTRIES_EN;

  const inputClass =
    "w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-green focus:border-transparent transition-all dark:border-slate-700 dark:bg-slate-800 dark:text-white dark:placeholder-slate-500 disabled:opacity-50 disabled:cursor-not-allowed";
  const labelClass =
    "block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1";

  if (success) {
    return (
      <div className="flex flex-col items-center gap-4 rounded-2xl border border-green-200 bg-green-50 p-8 text-center dark:border-green-800 dark:bg-green-900/20">
        <CheckCircle className="h-12 w-12 text-green-600 dark:text-green-400" />
        <h3 className="text-xl font-bold text-green-800 dark:text-green-200">
          {isAr ? "تم تسجيلك بنجاح!" : "Application Submitted!"}
        </h3>
        <p className="text-green-700 dark:text-green-300">
          {isAr
            ? "سنراجع طلبك ونتواصل معك خلال 48 ساعة مع رمز الإحالة الخاص بك."
            : "We'll review your application and reach out within 48 hours with your unique referral code."}
        </p>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-5"
      dir={isAr ? "rtl" : "ltr"}
    >
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <div>
          <label className={labelClass}>
            {isAr ? "الاسم الكامل *" : "Full Name *"}
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              setError(null);
            }}
            placeholder={isAr ? "أحمد محمد" : "Ahmed Mohammed"}
            required
            disabled={isSubmitting}
            className={inputClass}
          />
        </div>
        <div>
          <label className={labelClass}>
            {isAr ? "البريد الإلكتروني *" : "Email *"}
          </label>
          <input
            type="email"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              setError(null);
            }}
            placeholder={isAr ? "ahmed@company.com" : "ahmed@company.com"}
            required
            disabled={isSubmitting}
            className={inputClass}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <div>
          <label className={labelClass}>
            {isAr ? "رقم الهاتف *" : "Phone Number *"}
          </label>
          <input
            type="tel"
            value={phone}
            onChange={(e) => {
              setPhone(e.target.value);
              setError(null);
            }}
            placeholder={isAr ? "+974 5000 0000" : "+974 5000 0000"}
            required
            disabled={isSubmitting}
            className={inputClass}
          />
        </div>
        <div>
          <label className={labelClass}>
            {isAr ? "اسم الشركة *" : "Company Name *"}
          </label>
          <input
            type="text"
            value={company}
            onChange={(e) => {
              setCompany(e.target.value);
              setError(null);
            }}
            placeholder={isAr ? "شركة التقنية" : "Tech Solutions LLC"}
            required
            disabled={isSubmitting}
            className={inputClass}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <div>
          <label className={labelClass}>
            {isAr ? "نوع الشركة *" : "Company Type *"}
          </label>
          <select
            value={companyType}
            onChange={(e) => {
              setCompanyType(e.target.value);
              setError(null);
            }}
            required
            disabled={isSubmitting}
            className={inputClass}
          >
            <option value="">
              {isAr ? "اختر نوع الشركة" : "Select company type"}
            </option>
            {companyTypes.map((label, i) => (
              <option key={companyTypeValues[i]} value={companyTypeValues[i]}>
                {label}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className={labelClass}>
            {isAr ? "الدولة *" : "Country *"}
          </label>
          <select
            value={country}
            onChange={(e) => {
              setCountry(e.target.value);
              setError(null);
            }}
            required
            disabled={isSubmitting}
            className={inputClass}
          >
            <option value="">{isAr ? "اختر الدولة" : "Select country"}</option>
            {countries.map((label, i) => (
              <option key={countryValues[i]} value={countryValues[i]}>
                {label}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div>
        <label className={labelClass}>
          {isAr ? "الموقع الإلكتروني (اختياري)" : "Website (optional)"}
        </label>
        <input
          type="url"
          value={website}
          onChange={(e) => setWebsite(e.target.value)}
          placeholder="https://example.com"
          disabled={isSubmitting}
          className={inputClass}
        />
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-600 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">
          <AlertCircle className="h-4 w-4 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}

      <button
        type="submit"
        disabled={isSubmitting}
        className="w-full rounded-xl bg-gradient-to-r from-brand-green to-emerald-500 px-8 py-4 text-lg font-semibold text-white transition-all hover:from-green-600 hover:to-emerald-600 focus:outline-none focus:ring-2 focus:ring-brand-green focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {isSubmitting ? (
          <span className="inline-flex items-center gap-2">
            <Loader2 className="h-5 w-5 animate-spin" />
            {isAr ? "جاري الإرسال..." : "Submitting..."}
          </span>
        ) : isAr ? (
          "سجّل كشريك الآن"
        ) : (
          "Apply to Become a Partner"
        )}
      </button>

      <p className="text-center text-xs text-slate-500 dark:text-slate-400">
        {isAr
          ? "بتقديم هذا النموذج، أنت توافق على شروط برنامج الشركاء وسياسة الخصوصية."
          : "By submitting, you agree to our Partner Program Terms and Privacy Policy."}
      </p>
    </form>
  );
}
