"use client";

import { useState, useEffect, Suspense } from "react";
import { useUser } from "@clerk/nextjs";
import { useSearchParams, useParams } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import { signupStorage } from "@/lib/storage";

// Sectors must match exactly what we offer — keep in sync with lib/config/content/navigation.ts
const INDUSTRIES: { value: string; label: string; arLabel: string }[] = [
  { value: "health_care", label: "Health & Care", arLabel: "الصحة والرعاية" },
  {
    value: "beauty_wellness",
    label: "Beauty & Wellness",
    arLabel: "الجمال والعافية",
  },
  {
    value: "food_hospitality",
    label: "Food, Hospitality & Stays",
    arLabel: "الطعام والضيافة والإقامة",
  },
  {
    value: "retail_services",
    label: "Retail & Services",
    arLabel: "التجزئة والخدمات",
  },
  {
    value: "property_facilities",
    label: "Property & Facilities",
    arLabel: "العقارات والمرافق",
  },
  {
    value: "mobility_automotive",
    label: "Mobility & Automotive",
    arLabel: "التنقل والسيارات",
  },
  {
    value: "home_services_trades",
    label: "Home Services & Trades",
    arLabel: "خدمات المنازل والحرف",
  },
  { value: "education", label: "Education", arLabel: "التعليم" },
  {
    value: "events_venues",
    label: "Events & Venues",
    arLabel: "الفعاليات والقاعات",
  },
  {
    value: "pet_services",
    label: "Pet Services",
    arLabel: "خدمات الحيوانات الأليفة",
  },
  {
    value: "nonprofit_community",
    label: "Nonprofit/Community",
    arLabel: "المنظمات غير الربحية",
  },
  { value: "public_sector", label: "Public Sector", arLabel: "القطاع العام" },
  { value: "other", label: "Other", arLabel: "أخرى" },
];

const COMPANY_SIZES = ["1-5", "6-20", "21-50", "51-200", "200+"];

const GCC_COUNTRIES = [
  { value: "QA", label: "Qatar" },
  { value: "SA", label: "Saudi Arabia" },
  { value: "AE", label: "UAE" },
  { value: "KW", label: "Kuwait" },
  { value: "BH", label: "Bahrain" },
  { value: "OM", label: "Oman" },
];

// Prices in QAR — only QAR is supported by the checkout API
// priceId is intentionally empty — the server resolves it from id + billing period
const SETUP_FEE = "919";

const PLANS = [
  {
    id: "tier1",
    name: "Starter",
    nameAr: "المبتدئ",
    price: "827",
    currency: "QAR",
    period: "monthly",
    popular: false,
    features: [
      "AI Agent for FAQ & Auto-Reply",
      "Automated Appointment Booking",
      "Admin Dashboard",
      "WhatsApp Integration",
      "Basic Analytics",
    ],
    featuresAr: [
      "وكيل ذكاء اصطناعي للأسئلة والردود",
      "حجز المواعيد الآلي",
      "لوحة تحكم للمدير",
      "تكامل واتساب",
      "تحليلات أساسية",
    ],
  },
  {
    id: "tier2",
    name: "Professional",
    nameAr: "المحترف",
    price: "966",
    currency: "QAR",
    period: "monthly",
    popular: true,
    features: [
      "Everything in Starter",
      "Send & Receive Quotations",
      "CRM Dashboard",
      "Google & Third-Party Integrations",
      "Deposit Management",
    ],
    featuresAr: [
      "كل ما في المبتدئ",
      "إرسال واستقبال عروض الأسعار",
      "لوحة تحكم CRM",
      "تكامل مع Google والجهات الخارجية",
      "إدارة العربون",
    ],
  },
  {
    id: "tier3",
    name: "Business",
    nameAr: "الأعمال",
    price: "1,150",
    currency: "QAR",
    period: "monthly",
    popular: false,
    features: [
      "Everything in Professional",
      "Multi-Staff Login",
      "Recurring Appointments",
      "Multiple Appointments Setup",
      "AI Voice Receptionist",
    ],
    featuresAr: [
      "كل ما في المحترف",
      "تسجيل دخول متعدد للموظفين",
      "المواعيد المتكررة",
      "إعداد مواعيد متعددة",
      "مستقبل صوتي بالذكاء الاصطناعي",
    ],
  },
];

interface StepOneData {
  companyName: string;
  industry: string;
  companySize: string;
  gccCountry: string;
}

function SetupWizard({ lang }: { lang: Lang }) {
  const searchParams = useSearchParams();
  const urlUserId = searchParams?.get("userId") || "";
  const skipPayment = searchParams?.get("skipPayment") === "true";
  const { user, isLoaded } = useUser();
  const dir = UI[lang].dir;
  const isAr = lang === "ar";

  const [step, setStep] = useState<1 | 2>(1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedPlan, setSelectedPlan] = useState<string>("tier2");
  const [planFromPricing, setPlanFromPricing] = useState(false);
  const [storedCurrency, setStoredCurrency] = useState<string>("");
  const [storedBillingPeriod, setStoredBillingPeriod] = useState<string>("");
  const [csrfToken, setCsrfToken] = useState<string>("");
  // userId from URL param is preferred; falls back to value returned by company-info API
  const [resolvedUserId, setResolvedUserId] = useState(urlUserId);

  const [stepOneData, setStepOneData] = useState<StepOneData>({
    companyName: "",
    industry: "",
    companySize: "",
    gccCountry: "QA",
  });

  // Fetch CSRF token on mount
  useEffect(() => {
    fetch("/api/auth/csrf")
      .then((r) => r.json())
      .then((data: { csrfToken?: string }) =>
        setCsrfToken(data.csrfToken || ""),
      )
      .catch(() => {});
  }, []);

  // Read pre-selected plan from localStorage (set by pricing page)
  useEffect(() => {
    const stored = signupStorage.get();
    const tierId = stored?.plan?.tierId;
    if (tierId && ["tier1", "tier2", "tier3"].includes(tierId)) {
      setSelectedPlan(tierId);
      setPlanFromPricing(true);
      if (stored?.plan?.currency) setStoredCurrency(stored.plan.currency);
      if (stored?.plan?.billingPeriod)
        setStoredBillingPeriod(stored.plan.billingPeriod);
    }
  }, []);

  const userEmail = user?.emailAddresses[0]?.emailAddress || "";
  const userName =
    [user?.firstName, user?.lastName].filter(Boolean).join(" ") || "";

  async function handleStepOneSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!userEmail) {
      setError(
        isAr
          ? "انتهت الجلسة. يرجى تسجيل الدخول مرة أخرى."
          : "Session expired. Please sign in again.",
      );
      return;
    }

    if (
      !stepOneData.companyName ||
      !stepOneData.industry ||
      !stepOneData.companySize ||
      !stepOneData.gccCountry
    ) {
      setError(
        isAr
          ? "يرجى ملء جميع الحقول المطلوبة"
          : "Please fill all required fields",
      );
      return;
    }

    setIsLoading(true);
    try {
      const res = await fetchWithCSRF("/api/onboarding/company-info", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          email: userEmail,
          companyName: stepOneData.companyName,
          industry: stepOneData.industry,
          companySize: stepOneData.companySize,
          gccCountry: stepOneData.gccCountry,
        }),
      });

      const data = (await res.json().catch(() => ({}))) as {
        error?: string;
        userId?: string;
      };

      if (!res.ok) {
        throw new Error(data.error || "Failed to save company information");
      }

      // Store userId returned by the API so checkout has it (even if URL param was absent)
      if (data.userId && !resolvedUserId) {
        setResolvedUserId(data.userId);
      }

      if (skipPayment) {
        const completeRes = await fetchWithCSRF("/api/onboarding/complete", {
          method: "POST",
          headers: {
            "x-csrf-token": csrfToken,
          },
        });

        if (!completeRes.ok) {
          const completeData = (await completeRes.json().catch(() => ({}))) as {
            error?: string;
          };
          throw new Error(
            completeData.error || "Failed to finalize onboarding",
          );
        }

        window.location.href = `/${lang}/dashboard`;
        return;
      }

      if (planFromPricing) {
        await handleCheckout();
      } else {
        setStep(2);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleCheckout() {
    setIsLoading(true);
    setError(null);
    try {
      const plan = PLANS.find((p) => p.id === selectedPlan) || PLANS[1];
      const successUrl = `${window.location.origin}/${lang}/signup/success`;

      const res = await fetchWithCSRF("/api/signup/checkout", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          userId: resolvedUserId,
          tierId: plan.id,
          stripePriceId: "",
          billingPeriod: storedBillingPeriod || plan.period,
          currency: storedCurrency || plan.currency,
          email: userEmail,
          companyName: stepOneData.companyName,
          goals: [],
          language: lang,
          successUrl,
        }),
      });

      const data = (await res.json()) as {
        error?: string;
        sessionUrl?: string;
        url?: string;
      };

      if (!res.ok) {
        throw new Error(data.error || "Failed to create checkout session");
      }

      if (data.sessionUrl || data.url) {
        window.location.href = data.sessionUrl || data.url!;
      } else {
        throw new Error("No checkout URL returned");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleStepTwoSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!userEmail) {
      setError("Session error. Please refresh and try again.");
      return;
    }

    await handleCheckout();
  }

  if (!isLoaded) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#0F9972]" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50 px-4 py-12" dir={dir}>
      <div className="max-w-xl mx-auto">
        {/* Logo */}
        <div className="text-center mb-8">
          <BrandLogo href={`/${lang}`} size="lg" />
        </div>

        {/* Progress indicator */}
        <div className="flex items-center gap-3 mb-8 justify-center">
          <div
            className={`h-2 w-20 rounded-full ${step >= 1 ? "bg-[#0F9972]" : "bg-slate-200"}`}
          />
          {!skipPayment && !planFromPricing && (
            <div
              className={`h-2 w-20 rounded-full ${step >= 2 ? "bg-[#0F9972]" : "bg-slate-200"}`}
            />
          )}
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-8">
          {step === 1 ? (
            <>
              <h1 className="text-xl font-semibold text-slate-900 mb-1">
                {isAr ? "معلومات الشركة" : "Company Information"}
              </h1>
              <p className="text-sm text-slate-500 mb-6">
                {isAr
                  ? "أخبرنا عن شركتك حتى نتمكن من تخصيص تجربتك"
                  : "Tell us about your business so we can personalize your experience"}
              </p>

              {/* User info (read-only) */}
              <div className="mb-4 p-3 bg-slate-50 rounded-lg text-sm text-slate-600">
                <span className="font-medium">{userName}</span> — {userEmail}
              </div>

              <form onSubmit={handleStepOneSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "اسم الشركة *" : "Company Name *"}
                  </label>
                  <input
                    type="text"
                    required
                    value={stepOneData.companyName}
                    onChange={(e) =>
                      setStepOneData({
                        ...stepOneData,
                        companyName: e.target.value,
                      })
                    }
                    className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-[#0F9972] focus:border-[#0F9972] outline-none"
                    placeholder={
                      isAr ? "مثال: عيادة النور" : "e.g. Al Noor Clinic"
                    }
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    {isAr ? "القطاع *" : "Industry *"}
                  </label>
                  <select
                    required
                    value={stepOneData.industry}
                    onChange={(e) =>
                      setStepOneData({
                        ...stepOneData,
                        industry: e.target.value,
                      })
                    }
                    className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-[#0F9972] focus:border-[#0F9972] outline-none"
                  >
                    <option value="">
                      {isAr ? "اختر القطاع" : "Select industry"}
                    </option>
                    {INDUSTRIES.map((i) => (
                      <option key={i.value} value={i.value}>
                        {isAr ? i.arLabel : i.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "حجم الشركة *" : "Company Size *"}
                    </label>
                    <select
                      required
                      value={stepOneData.companySize}
                      onChange={(e) =>
                        setStepOneData({
                          ...stepOneData,
                          companySize: e.target.value,
                        })
                      }
                      className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-[#0F9972] focus:border-[#0F9972] outline-none"
                    >
                      <option value="">{isAr ? "الحجم" : "Size"}</option>
                      {COMPANY_SIZES.map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {isAr ? "الدولة *" : "Country *"}
                    </label>
                    <select
                      required
                      value={stepOneData.gccCountry}
                      onChange={(e) =>
                        setStepOneData({
                          ...stepOneData,
                          gccCountry: e.target.value,
                        })
                      }
                      className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-[#0F9972] focus:border-[#0F9972] outline-none"
                    >
                      {GCC_COUNTRIES.map((c) => (
                        <option key={c.value} value={c.value}>
                          {c.label}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                {error && (
                  <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                    {error}
                  </p>
                )}

                <button
                  type="submit"
                  disabled={isLoading}
                  className="w-full bg-[#0F9972] hover:bg-[#0D8761] text-white font-medium py-2.5 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading
                    ? isAr
                      ? "جاري الحفظ..."
                      : "Saving..."
                    : skipPayment
                      ? isAr
                        ? "حفظ والمتابعة للوحة التحكم"
                        : "Save & Go to Dashboard"
                      : planFromPricing
                        ? isAr
                          ? "المتابعة للدفع"
                          : "Continue to Payment"
                        : isAr
                          ? "التالي"
                          : "Continue"}
                </button>
              </form>
            </>
          ) : (
            <>
              <h1 className="text-xl font-semibold text-slate-900 mb-1">
                {isAr ? "اختر خطتك" : "Choose Your Plan"}
              </h1>
              <p className="text-sm text-slate-500 mb-6">
                {isAr
                  ? "ابدأ تجربة مجانية لمدة 14 يوماً، لا حاجة لبطاقة ائتمانية"
                  : "Start your 14-day free trial — no credit card required"}
              </p>

              <form onSubmit={handleStepTwoSubmit} className="space-y-3">
                {PLANS.map((plan) => (
                  <div
                    key={plan.id}
                    onClick={() => setSelectedPlan(plan.id)}
                    className={`border-2 rounded-xl p-4 cursor-pointer transition-all relative ${
                      selectedPlan === plan.id
                        ? "border-[#0F9972] bg-[#0F9972]/5"
                        : plan.popular
                          ? "border-[#0F9972]/40 hover:border-[#0F9972]"
                          : "border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    {plan.popular && (
                      <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                        <span className="bg-[#0F9972] text-white text-xs font-semibold px-3 py-1 rounded-full whitespace-nowrap">
                          {isAr ? "الأكثر شعبية" : "Most Popular"}
                        </span>
                      </div>
                    )}
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <p className="font-semibold text-slate-900">
                          {isAr ? plan.nameAr : plan.name}
                        </p>
                        <p className="text-2xl font-bold text-[#0F9972] mt-1">
                          {plan.price}{" "}
                          <span className="text-sm font-normal text-slate-500">
                            {plan.currency}/{isAr ? "شهر" : "mo"}
                          </span>
                        </p>
                        <p className="text-xs text-slate-400 mt-0.5">
                          {isAr
                            ? `+ ${SETUP_FEE} QAR رسوم إعداد (مرة واحدة)`
                            : `+ ${SETUP_FEE} QAR setup fee (one-time)`}
                        </p>
                        <ul className="mt-2 space-y-1">
                          {(isAr ? plan.featuresAr : plan.features).map((f) => (
                            <li
                              key={f}
                              className="text-xs text-slate-600 flex items-center gap-1"
                            >
                              <span className="text-[#0F9972]">✓</span> {f}
                            </li>
                          ))}
                        </ul>
                      </div>
                      <div
                        className={`w-5 h-5 rounded-full border-2 flex-shrink-0 mt-1 ml-3 ${
                          selectedPlan === plan.id
                            ? "border-[#0F9972] bg-[#0F9972]"
                            : "border-slate-300"
                        }`}
                      />
                    </div>
                  </div>
                ))}

                {error && (
                  <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2">
                    {error}
                  </p>
                )}

                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setStep(1)}
                    className="flex-1 border border-slate-300 text-slate-700 font-medium py-2.5 rounded-lg hover:bg-slate-50 transition-colors"
                  >
                    {isAr ? "رجوع" : "Back"}
                  </button>
                  <button
                    type="submit"
                    disabled={isLoading || !selectedPlan}
                    className="flex-2 flex-1 bg-[#0F9972] hover:bg-[#0D8761] text-white font-medium py-2.5 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isLoading
                      ? isAr
                        ? "جاري المعالجة..."
                        : "Processing..."
                      : isAr
                        ? "المتابعة للدفع"
                        : "Continue to Payment"}
                  </button>
                </div>
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default function OnboardingSetupPage() {
  const params = useParams();
  const lang = (params?.lang as Lang) || "en";

  return (
    <Suspense
      fallback={
        <div className="min-h-screen flex items-center justify-center bg-slate-50">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#0F9972]" />
        </div>
      }
    >
      <SetupWizard lang={lang} />
    </Suspense>
  );
}
