"use client";

import { useState, useEffect } from "react";
import {
  X,
  ArrowUpRight,
  ArrowDownRight,
  CreditCard,
  Loader2,
  CheckCircle,
  ShieldCheck,
  Calendar,
  Sparkles,
  AlertCircle,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import {
  CURRENCY_RATES,
  calculateYearlyTotal,
  getDaysUntilBilling,
  getTierPriceQARDisplay,
} from "@/lib/utils/pricing-helpers";
import type {
  TierId,
  BillingPeriod,
  PlanChangePreviewResponse,
  PlanChangeExecuteResponse,
} from "@/lib/types/plan-change.types";
import { TIER_ORDER } from "@/lib/types/plan-change.types";

interface PlanChangeModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  currentTierId: TierId;
  currentBillingPeriod: BillingPeriod;
  currentPeriodEnd: string;
  onSuccess?: (newTierId: TierId) => void;
}

const QAR_RATE = CURRENCY_RATES.QAR;

export default function PlanChangeModal({
  lang,
  isOpen,
  onClose,
  currentTierId,
  currentBillingPeriod,
  currentPeriodEnd,
  onSuccess,
}: PlanChangeModalProps) {
  const isAr = lang === "ar";

  // State
  const [step, setStep] = useState<"select" | "preview" | "success">("select");
  const [selectedTier, setSelectedTier] = useState<TierId | null>(null);
  const [billingPeriod, setBillingPeriod] =
    useState<BillingPeriod>(currentBillingPeriod);
  const [preview, setPreview] = useState<
    PlanChangePreviewResponse["preview"] | null
  >(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [confirmed, setConfirmed] = useState(false);
  const [successData, setSuccessData] =
    useState<PlanChangeExecuteResponse | null>(null);

  // Translations
  const t = {
    title: isAr ? "تغيير الخطة" : "Change Plan",
    subtitle: isAr
      ? "اختر خطة جديدة لاشتراكك"
      : "Select a new plan for your subscription",
    currentPlan: isAr ? "الخطة الحالية" : "Current Plan",
    upgrade: isAr ? "ترقية" : "Upgrade",
    downgrade: isAr ? "تخفيض" : "Downgrade",
    select: isAr ? "اختيار" : "Select",
    daysRemaining: isAr ? "يوم متبقي" : "days remaining",
    prorationPreview: isAr ? "معاينة التسوية" : "Proration Preview",
    creditFromCurrent: isAr
      ? "رصيد من الخطة الحالية"
      : "Credit from current plan",
    chargeForNew: isAr ? "رسوم الخطة الجديدة" : "Charge for new plan",
    netAmount: isAr ? "المبلغ الصافي" : "Net Amount",
    toPayNow: isAr ? "للدفع الآن" : "to pay now",
    creditApplied: isAr ? "رصيد مطبق" : "credit applied",
    nextBilling: isAr ? "الفاتورة القادمة" : "Next Billing",
    confirmChange: isAr ? "تأكيد التغيير" : "Confirm Change",
    cancel: isAr ? "إلغاء" : "Cancel",
    back: isAr ? "رجوع" : "Back",
    processing: isAr ? "جاري المعالجة..." : "Processing...",
    confirmCheckbox: isAr
      ? "أفهم أنه سيتم تحديث اشتراكي وقد يتم محاسبتي على الفور"
      : "I understand my subscription will be updated and I may be charged immediately",
    monthly: isAr ? "شهري" : "Monthly",
    yearly: isAr ? "سنوي" : "Yearly",
    perMonth: isAr ? "/شهر" : "/mo",
    perYear: isAr ? "/سنة" : "/yr",
    popular: isAr ? "الأكثر شعبية" : "Most Popular",
    error: isAr ? "حدث خطأ" : "An error occurred",
    securePayment: isAr ? "دفع آمن عبر Stripe" : "Secure payment via Stripe",
    success: isAr ? "تم بنجاح!" : "Success!",
    successMessage: isAr
      ? "تم تغيير خطتك بنجاح"
      : "Your plan has been changed successfully",
    close: isAr ? "إغلاق" : "Close",
    viewBilling: isAr ? "عرض الفواتير" : "View Billing",
    savingsNote: isAr
      ? "وفر 7% مع الفوترة السنوية"
      : "Save 7% with yearly billing",
  };

  // Reset state when modal opens/closes
  useEffect(() => {
    if (isOpen) {
      setStep("select");
      setSelectedTier(null);
      setBillingPeriod(currentBillingPeriod);
      setPreview(null);
      setError(null);
      setConfirmed(false);
      setSuccessData(null);
    }
  }, [isOpen, currentBillingPeriod]);

  // Fetch preview when tier is selected
  const fetchPreview = async (tierId: TierId) => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `/api/subscription/preview-change?newTierId=${tierId}&billingPeriod=${billingPeriod}`,
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to load preview");
      }

      const data: PlanChangePreviewResponse = await response.json();
      setPreview(data.preview);
      setSelectedTier(tierId);
      setStep("preview");
    } catch (err) {
      setError(err instanceof Error ? err.message : t.error);
    } finally {
      setLoading(false);
    }
  };

  // Execute plan change
  const executeChange = async () => {
    if (!selectedTier || !preview) return;
    setLoading(true);
    setError(null);

    try {
      // Get CSRF token from cookie
      const csrfToken = document.cookie
        .split("; ")
        .find((row) => row.startsWith("csrf-token="))
        ?.split("=")[1];

      const response = await fetch("/api/billing/change-plan", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...(csrfToken && { "x-csrf-token": csrfToken }),
        },
        body: JSON.stringify({
          newTierId: selectedTier,
          billingPeriod,
          confirmedAmount: preview.proration.netAmount,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to change plan");
      }

      const result: PlanChangeExecuteResponse = await response.json();
      setSuccessData(result);
      setStep("success");
      onSuccess?.(selectedTier);
    } catch (err) {
      setError(err instanceof Error ? err.message : t.error);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  const daysRemaining = getDaysUntilBilling(new Date(currentPeriodEnd));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-slate-900/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-3xl max-h-[90vh] overflow-hidden rounded-2xl bg-white shadow-2xl">
        {/* Header */}
        <div className="px-6 py-4 border-b border-slate-200 bg-gradient-to-r from-brand-green/10 to-emerald-50 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-brand-green rounded-xl">
              <Sparkles className="w-5 h-5 text-white" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-slate-900">
                {t.title}
              </h3>
              <p className="text-sm text-slate-500">{t.subtitle}</p>
            </div>
          </div>
          <button
            type="button"
            aria-label="Close"
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
          {/* Error Message */}
          {error && (
            <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-4 flex items-center gap-3">
              <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
              <p className="text-sm text-red-700">{error}</p>
            </div>
          )}

          {/* Step 1: Plan Selection */}
          {step === "select" && (
            <div className="space-y-6">
              {/* Billing Period Toggle */}
              <div className="flex items-center justify-center gap-2">
                <button
                  onClick={() => setBillingPeriod("monthly")}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                    billingPeriod === "monthly"
                      ? "bg-brand-green text-white"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  {t.monthly}
                </button>
                <button
                  onClick={() => setBillingPeriod("yearly")}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                    billingPeriod === "yearly"
                      ? "bg-brand-green text-white"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  {t.yearly}
                </button>
                {billingPeriod === "yearly" && (
                  <span className="ml-2 text-xs text-emerald-600 font-medium">
                    {t.savingsNote}
                  </span>
                )}
              </div>

              {/* Current Plan Info */}
              <div className="bg-slate-50 rounded-lg p-4 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Calendar className="w-5 h-5 text-slate-400" />
                  <div>
                    <p className="text-sm text-slate-600">
                      {t.currentPlan}:{" "}
                      <span className="font-semibold text-slate-900">
                        {
                          PRICING_TIERS.find((t) => t.id === currentTierId)?.[
                            isAr ? "nameAr" : "nameEn"
                          ]
                        }
                      </span>
                    </p>
                    <p className="text-xs text-slate-500">
                      {daysRemaining} {t.daysRemaining}
                    </p>
                  </div>
                </div>
              </div>

              {/* Plan Cards */}
              <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                {PRICING_TIERS.filter((t) =>
                  ["tier1", "tier2", "tier3"].includes(t.id),
                ).map((tier) => {
                  const tierId = tier.id as TierId;
                  const isCurrent = tierId === currentTierId;
                  const isUpgrade =
                    TIER_ORDER[tierId] > TIER_ORDER[currentTierId];
                  const isDowngrade =
                    TIER_ORDER[tierId] < TIER_ORDER[currentTierId];
                  const priceQAR = getTierPriceQARDisplay(
                    tierId,
                    billingPeriod,
                  );

                  return (
                    <div
                      key={tier.id}
                      className={`relative rounded-xl border-2 p-4 transition-all ${
                        isCurrent
                          ? "border-brand-green bg-brand-green/5 opacity-75"
                          : "border-slate-200 hover:border-brand-green hover:shadow-md cursor-pointer"
                      }`}
                      onClick={() =>
                        !isCurrent && !loading && fetchPreview(tierId)
                      }
                    >
                      {/* Popular Badge */}
                      {tier.popular && (
                        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                          <span className="bg-brand-green text-white text-xs font-semibold px-3 py-1 rounded-full">
                            {t.popular}
                          </span>
                        </div>
                      )}

                      {/* Current Plan Badge */}
                      {isCurrent && (
                        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                          <span className="bg-slate-600 text-white text-xs font-semibold px-3 py-1 rounded-full">
                            {t.currentPlan}
                          </span>
                        </div>
                      )}

                      <div className="pt-2">
                        <h4 className="text-lg font-semibold text-slate-900">
                          {isAr ? tier.nameAr : tier.nameEn}
                        </h4>
                        <div className="mt-2">
                          <span className="text-2xl font-bold text-slate-900">
                            QAR {priceQAR}
                          </span>
                          <span className="text-sm text-slate-500">
                            {billingPeriod === "yearly"
                              ? t.perYear
                              : t.perMonth}
                          </span>
                        </div>

                        {/* Features (first 3) */}
                        <ul className="mt-4 space-y-2">
                          {(isAr ? tier.featuresAr : tier.featuresEn)
                            .slice(0, 3)
                            .map((feature, idx) => (
                              <li
                                key={idx}
                                className="flex items-center gap-2 text-xs text-slate-600"
                              >
                                <CheckCircle className="w-3.5 h-3.5 text-brand-green flex-shrink-0" />
                                <span className="line-clamp-1">{feature}</span>
                              </li>
                            ))}
                        </ul>

                        {/* Action Button */}
                        <div className="mt-4">
                          {isCurrent ? (
                            <div className="w-full py-2 text-center text-sm text-slate-500">
                              {t.currentPlan}
                            </div>
                          ) : (
                            <button
                              disabled={loading}
                              className={`w-full flex items-center justify-center gap-2 py-2 px-4 rounded-lg text-sm font-medium transition-colors ${
                                isUpgrade
                                  ? "bg-brand-green text-white hover:bg-brand-greenHover"
                                  : "bg-slate-100 text-slate-700 hover:bg-slate-200"
                              } disabled:opacity-50`}
                            >
                              {loading && selectedTier === tierId ? (
                                <Loader2 className="w-4 h-4 animate-spin" />
                              ) : isUpgrade ? (
                                <>
                                  <ArrowUpRight className="w-4 h-4" />
                                  {t.upgrade}
                                </>
                              ) : (
                                <>
                                  <ArrowDownRight className="w-4 h-4" />
                                  {t.downgrade}
                                </>
                              )}
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Step 2: Proration Preview */}
          {step === "preview" && preview && (
            <div className="space-y-6">
              {/* Plan Change Summary */}
              <div className="bg-slate-50 rounded-xl p-5">
                <div className="flex items-center justify-between">
                  <div className="text-center flex-1">
                    <p className="text-xs text-slate-500 mb-1">
                      {t.currentPlan}
                    </p>
                    <p className="font-semibold text-slate-900">
                      {isAr
                        ? preview.currentPlan.nameAr
                        : preview.currentPlan.nameEn}
                    </p>
                    <p className="text-sm text-slate-600">
                      QAR {Math.round(preview.currentPlan.priceInCurrency)}
                      {currentBillingPeriod === "yearly"
                        ? t.perYear
                        : t.perMonth}
                    </p>
                  </div>
                  <div className="px-4">
                    {preview.isUpgrade ? (
                      <ArrowUpRight className="w-6 h-6 text-brand-green" />
                    ) : (
                      <ArrowDownRight className="w-6 h-6 text-amber-500" />
                    )}
                  </div>
                  <div className="text-center flex-1">
                    <p className="text-xs text-slate-500 mb-1">
                      {preview.isUpgrade ? t.upgrade : t.downgrade}
                    </p>
                    <p className="font-semibold text-slate-900">
                      {isAr ? preview.newPlan.nameAr : preview.newPlan.nameEn}
                    </p>
                    <p className="text-sm text-slate-600">
                      QAR {Math.round(preview.newPlan.priceInCurrency)}
                      {billingPeriod === "yearly" ? t.perYear : t.perMonth}
                    </p>
                  </div>
                </div>
              </div>

              {/* Proration Breakdown */}
              <div className="rounded-xl border border-slate-200 overflow-hidden">
                <div className="bg-slate-50 px-5 py-3 border-b border-slate-200">
                  <h4 className="font-semibold text-slate-900">
                    {t.prorationPreview}
                  </h4>
                  <p className="text-xs text-slate-500 mt-1">
                    {preview.proration.daysRemaining} {t.daysRemaining}
                  </p>
                </div>
                <div className="p-5 space-y-4">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-slate-600">
                      {t.creditFromCurrent}
                    </span>
                    <span className="font-medium text-emerald-600">
                      - QAR{" "}
                      {(preview.proration.creditFromCurrent / 100).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-slate-600">{t.chargeForNew}</span>
                    <span className="font-medium text-slate-900">
                      + QAR {(preview.proration.chargeForNew / 100).toFixed(2)}
                    </span>
                  </div>
                  <div className="border-t border-slate-200 pt-4 flex items-center justify-between">
                    <span className="font-semibold text-slate-900">
                      {t.netAmount}
                    </span>
                    <span
                      className={`text-xl font-bold ${
                        preview.proration.netAmount >= 0
                          ? "text-brand-green"
                          : "text-emerald-600"
                      }`}
                    >
                      {preview.proration.netAmount >= 0 ? "" : "-"} QAR{" "}
                      {Math.abs(preview.proration.netAmount / 100).toFixed(2)}
                    </span>
                  </div>
                  <p className="text-xs text-slate-500 text-center">
                    {preview.proration.netAmount >= 0
                      ? t.toPayNow
                      : t.creditApplied}
                  </p>
                </div>
              </div>

              {/* Next Billing Info */}
              <div className="bg-blue-50 rounded-lg p-4">
                <h5 className="text-sm font-semibold text-blue-800 flex items-center gap-2">
                  <Calendar className="w-4 h-4" />
                  {t.nextBilling}
                </h5>
                <p className="mt-2 text-sm text-blue-700">
                  {isAr ? preview.summary.ar : preview.summary.en}
                </p>
              </div>

              {/* Confirmation Checkbox */}
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  checked={confirmed}
                  onChange={(e) => setConfirmed(e.target.checked)}
                  className="mt-1 w-4 h-4 rounded border-slate-300 text-brand-green focus:ring-brand-green"
                />
                <span className="text-sm text-slate-600">
                  {t.confirmCheckbox}
                </span>
              </label>
            </div>
          )}

          {/* Step 3: Success */}
          {step === "success" && successData && (
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-8 h-8 text-emerald-600" />
              </div>
              <h3 className="text-xl font-semibold text-slate-900 mb-2">
                {t.success}
              </h3>
              <p className="text-slate-600 mb-6">
                {isAr ? successData.message.ar : successData.message.en}
              </p>
              <div className="flex items-center justify-center gap-3">
                <button
                  onClick={onClose}
                  className="px-6 py-2.5 bg-brand-green text-white rounded-lg font-medium hover:bg-brand-greenHover transition-colors"
                >
                  {t.close}
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        {step !== "success" && (
          <div className="px-6 py-4 border-t border-slate-200 bg-slate-50">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-xs text-slate-500">
                <ShieldCheck className="w-4 h-4" />
                {t.securePayment}
              </div>
              <div className="flex items-center gap-3">
                {step === "preview" && (
                  <button
                    onClick={() => {
                      setStep("select");
                      setPreview(null);
                      setSelectedTier(null);
                      setConfirmed(false);
                    }}
                    className="px-4 py-2.5 text-slate-600 hover:text-slate-800 hover:bg-slate-100 rounded-lg transition-colors font-medium"
                  >
                    {t.back}
                  </button>
                )}
                <button
                  onClick={onClose}
                  className="px-4 py-2.5 text-slate-600 hover:text-slate-800 hover:bg-slate-100 rounded-lg transition-colors font-medium"
                >
                  {t.cancel}
                </button>
                {step === "preview" && (
                  <button
                    onClick={executeChange}
                    disabled={!confirmed || loading}
                    className="flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-xl font-medium shadow-lg shadow-brand-green/25 hover:shadow-xl hover:shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? (
                      <Loader2 className="w-5 h-5 animate-spin" />
                    ) : (
                      <CreditCard className="w-5 h-5" />
                    )}
                    {loading ? t.processing : t.confirmChange}
                  </button>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
