"use client";

import { useEffect, useState } from "react";
import type { Lang } from "@/lib/config";
import type { BillingPeriod, Currency, TierId } from "@/lib/types/pricing";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import type { DashboardSubscriptionDetails } from "../types";

const tierOrder: TierId[] = ["tier1", "tier2", "tier3", "tier4", "tier5"];

interface PlanUpgradeModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  subscriptionData: DashboardSubscriptionDetails | null;
  currency: Currency;
  initialTier?: TierId;
  billingPeriod: BillingPeriod;
  onSuccess?: () => void;
}

interface PreviewResponse {
  amountDue: number;
  currency: string | null;
  nextPaymentAttempt: number | null;
  periodEnd: number;
  lineItems: Array<{
    id: string;
    description: string | null;
    amount: number;
    proration: boolean;
    period: { start: number; end: number };
  }>;
}

export function PlanUpgradeModal({
  lang,
  isOpen,
  onClose,
  subscriptionData,
  currency,
  initialTier,
  billingPeriod,
  onSuccess,
}: PlanUpgradeModalProps) {
  const [selectedTier, setSelectedTier] = useState<TierId | null>(
    initialTier ?? null,
  );
  const [preview, setPreview] = useState<PreviewResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const isAr = lang === "ar";
  const currentTier = subscriptionData?.subscription.tierId as
    | TierId
    | undefined;
  const currentIndex = currentTier ? tierOrder.indexOf(currentTier) : -1;

  const isDowngrade =
    initialTier && currentTier
      ? tierOrder.indexOf(initialTier) < tierOrder.indexOf(currentTier)
      : false;

  const tierOptions = PRICING_TIERS.filter((tier) => {
    if (!["tier1", "tier2", "tier3"].includes(tier.id)) return false;
    const tierIndex = tierOrder.indexOf(tier.id as TierId);
    return isDowngrade ? tierIndex < currentIndex : tierIndex > currentIndex;
  });
  const defaultTier = tierOptions[0]?.id as TierId | undefined;

  const formatAmount = (amount: number) => {
    const value = (amount || 0) / 100;
    return `${value.toFixed(2)} ${currency}`;
  };

  const handleConfirm = async () => {
    if (!selectedTier || !subscriptionData) {
      return;
    }
    setSubmitting(true);
    setError(null);
    setSuccessMessage(null);
    try {
      const response = await fetch("/api/subscription/upgrade", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include", // Include session cookie for authentication
        body: JSON.stringify({
          subscriptionId: subscriptionData.subscription.id,
          newTierId: selectedTier,
          billingPeriod,
          currency: currency.toLowerCase(),
        }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || "Upgrade failed");
      }

      setSuccessMessage(
        isDowngrade
          ? isAr
            ? "تم تخفيض الخطة بنجاح. سيتم تطبيق الرصيد على فاتورتك القادمة."
            : "Plan downgraded successfully. Credit will apply to next invoice."
          : isAr
            ? "تم إرسال طلب الترقية وسيتم تطبيقه فوراً."
            : "Upgrade submitted successfully.",
      );
      onSuccess?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Upgrade failed");
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    if (isOpen) {
      setSelectedTier(initialTier ?? null);
      setPreview(null);
      setSuccessMessage(null);
      setError(null);
    }
  }, [isOpen, initialTier]);

  useEffect(() => {
    if (isOpen && !initialTier && defaultTier) {
      setSelectedTier(defaultTier);
    }
  }, [isOpen, initialTier, defaultTier]);

  useEffect(() => {
    if (!isOpen || !selectedTier || !subscriptionData) {
      return;
    }

    async function loadPreview() {
      setLoading(true);
      setError(null);
      try {
        const params = new URLSearchParams({
          subscriptionId: subscriptionData.subscription.id,
          newTierId: selectedTier,
          billingPeriod,
          currency: currency.toLowerCase(),
        });
        const response = await fetch(
          `/api/subscription/upgrade/preview?${params.toString()}`,
          {
            credentials: "include", // Include session cookie for authentication
          },
        );
        if (!response.ok) {
          const data = await response.json();
          throw new Error(data.error || "Preview failed");
        }
        const data = await response.json();
        setPreview(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Preview failed");
      } finally {
        setLoading(false);
      }
    }

    loadPreview();
  }, [isOpen, selectedTier, subscriptionData, currency, billingPeriod]);

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 px-4">
      <div className="w-full max-w-2xl rounded-2xl bg-white p-6 shadow-2xl">
        <div className="mb-4 flex items-start justify-between">
          <div>
            <h3 className="text-xl font-semibold text-slate-900">
              {isDowngrade
                ? isAr
                  ? "تخفيض الخطة"
                  : "Downgrade your plan"
                : isAr
                  ? "ترقية الخطة"
                  : "Upgrade your plan"}
            </h3>
            <p className="text-sm text-slate-500">
              {isDowngrade
                ? isAr
                  ? "سيتم تطبيق الرصيد المتبقي على فاتورتك القادمة. لن تفقد المميزات حتى نهاية الدورة."
                  : "Credit will be applied to your next invoice. You will keep features until end of cycle."
                : isAr
                  ? "اختر باقة أعلى لفتح مزايا إضافية. سنعرض تكلفة اليوم قبل التأكيد."
                  : "Pick a higher tier to unlock more features. We will show cost before confirming."}
            </p>
          </div>
          <button
            onClick={onClose}
            className="rounded-full bg-slate-100 px-3 py-1 text-sm text-slate-600 hover:bg-slate-200"
          >
            ✕
          </button>
        </div>

        {tierOptions.length === 0 ? (
          <div className="mb-4 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
            {isDowngrade
              ? isAr
                ? "أنت بالفعل على أدنى باقة. لا توجد خيارات تخفيض متاحة."
                : "You are already on the lowest tier. No downgrade options available."
              : isAr
                ? "أنت بالفعل على أعلى باقة. تواصل مع فريق الدعم لحلول مخصصة."
                : "You are already on the highest tier. Contact support for bespoke options."}
          </div>
        ) : (
          <div className="mb-4 grid gap-3 sm:grid-cols-2">
            {tierOptions.map((tier) => (
              <button
                key={tier.id}
                onClick={() => setSelectedTier(tier.id as TierId)}
                className={`rounded-xl border px-4 py-3 text-left ${
                  selectedTier === tier.id
                    ? "border-brand-green bg-emerald-50"
                    : "border-slate-200 bg-slate-50"
                }`}
              >
                <p className="text-xs uppercase text-slate-500">
                  {isAr ? "الباقة" : "Plan"}
                </p>
                <p className="text-lg font-semibold text-slate-900">
                  {isAr ? tier.nameAr : tier.nameEn}
                </p>
                <p className="text-xs text-slate-500">
                  {isAr ? "يشمل:" : "Includes:"}{" "}
                  {(isAr ? tier.featuresAr : tier.featuresEn)[0]}
                </p>
              </button>
            ))}
          </div>
        )}

        <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
          <p className="text-sm font-semibold text-slate-900">
            {isAr ? "تفاصيل الفاتورة القادمة" : "Upcoming billing preview"}
          </p>
          {loading && (
            <p className="mt-2 text-xs text-slate-500">
              {isAr ? "جاري الحساب..." : "Calculating..."}
            </p>
          )}
          {error && <p className="mt-2 text-xs text-rose-600">{error}</p>}
          {preview && !loading && (
            <div className="mt-3 space-y-2 text-sm text-slate-600">
              <div className="flex items-center justify-between">
                <span>{isAr ? "مستحق اليوم" : "Due today"}</span>
                <span className="text-base font-semibold text-slate-900">
                  {formatAmount(preview.amountDue)}
                </span>
              </div>
              <div className="text-xs text-slate-500">
                {isAr
                  ? "يشمل فرق السعر مع الرصيد المتبقي من خطتك الحالية."
                  : "Includes prorated difference from your current plan."}
              </div>
              <div>
                <p className="text-xs font-semibold text-slate-500">
                  {isAr ? "تفاصيل بنود الفاتورة" : "Invoice breakdown"}
                </p>
                <ul className="mt-2 space-y-1 text-xs">
                  {preview.lineItems.map((item) => (
                    <li
                      key={item.id}
                      className="flex items-center justify-between"
                    >
                      <span>
                        {item.description}{" "}
                        {item.proration && (
                          <span className="text-slate-400">
                            ({isAr ? "نسبي" : "proration"})
                          </span>
                        )}
                      </span>
                      <span>{formatAmount(item.amount)}</span>
                    </li>
                  ))}
                </ul>
              </div>
              <div className="text-xs text-slate-500">
                {isAr ? "سيتكرر السحب التالي في " : "Next renewal will be on "}
                {new Date(preview.periodEnd * 1000).toLocaleDateString(
                  isAr ? "ar-SA" : "en-US",
                  {
                    month: "short",
                    day: "numeric",
                    year: "numeric",
                  },
                )}
              </div>
            </div>
          )}
        </div>

        {successMessage && (
          <div className="mt-3 rounded-lg bg-emerald-50 px-4 py-2 text-sm text-emerald-700">
            {successMessage}
          </div>
        )}

        <div className="mt-4 flex flex-wrap justify-end gap-3">
          <button
            onClick={onClose}
            className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-600 hover:border-slate-300"
          >
            {isAr ? "إلغاء" : "Cancel"}
          </button>
          <button
            onClick={handleConfirm}
            disabled={!selectedTier || submitting || loading}
            className={`rounded-lg px-5 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300 ${
              isDowngrade
                ? "bg-slate-600 hover:bg-slate-700"
                : "bg-brand-green hover:bg-brand-greenHover"
            }`}
          >
            {submitting
              ? isDowngrade
                ? isAr
                  ? "جاري التخفيض..."
                  : "Processing downgrade..."
                : isAr
                  ? "جاري الترقية..."
                  : "Upgrading..."
              : isDowngrade
                ? isAr
                  ? "تأكيد التخفيض"
                  : "Confirm downgrade"
                : isAr
                  ? "تأكيد الترقية"
                  : "Confirm upgrade"}
          </button>
        </div>
      </div>
    </div>
  );
}
