/**
 * Subscription Details Component
 * Displays current subscription information including payment method and setup fee
 */

"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import type { Lang } from "@/lib/config";
import PlanChangeModal from "./PlanChangeModal";
import type { TierId, BillingPeriod } from "@/lib/types/plan-change.types";

interface SubscriptionData {
  subscription: {
    id: string;
    tierId: string;
    status: string;
    billingPeriod: string;
    currentPeriodEnd: string;
    trialEndsAt: string | null;
    setupFeePaid: boolean;
    setupFeeAmount: number | null;
    setupFeePaidAt: string | null;
    paymentMethod: {
      brand: string;
      lastFour: string;
      id: string;
    } | null;
    stripeCustomerId: string;
    stripeSubscriptionId: string;
    cancelAtPeriodEnd: boolean;
    lastPaymentDate: string | null;
    paymentFailureCount: number;
  };
  user: {
    email: string;
    name: string;
    companyName: string;
  };
}

interface SubscriptionDetailsProps {
  lang: Lang;
  hideFullBillingLink?: boolean;
}

export default function SubscriptionDetails({
  lang,
  hideFullBillingLink = false,
}: SubscriptionDetailsProps) {
  const [data, setData] = useState<SubscriptionData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [portalLoading, setPortalLoading] = useState(false);
  const [showPlanChangeModal, setShowPlanChangeModal] = useState(false);

  const isAr = lang === "ar";

  const handleBillingPortal = async () => {
    setPortalLoading(true);
    try {
      const response = await fetch("/api/stripe/billing-portal", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          returnUrl: `${window.location.origin}/${lang}/dashboard?tab=billing`,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        alert(errorData.error || "Failed to open billing portal");
        return;
      }

      const { url } = await response.json();
      window.open(url, "_blank", "noopener,noreferrer");
    } catch (err) {
      console.error("Error opening billing portal:", err);
      alert(isAr ? "فشل فتح بوابة الفواتير" : "Failed to open billing portal");
    } finally {
      setPortalLoading(false);
    }
  };

  const fetchSubscription = useCallback(async () => {
    try {
      const response = await fetch("/api/subscription/details");
      if (!response.ok) {
        if (response.status === 404) {
          setError(isAr ? "لا يوجد اشتراك نشط" : "No active subscription");
        } else {
          throw new Error("Failed to fetch subscription");
        }
        return;
      }

      const result = await response.json();
      setData(result);
    } catch (err) {
      console.error("Error fetching subscription:", err);
      setError(
        isAr ? "فشل تحميل بيانات الاشتراك" : "Failed to load subscription",
      );
    } finally {
      setLoading(false);
    }
  }, [isAr]);

  useEffect(() => {
    fetchSubscription();
  }, [fetchSubscription]);

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <div className="animate-pulse space-y-4">
          <div className="h-4 bg-slate-200 rounded w-1/3"></div>
          <div className="h-6 bg-slate-200 rounded w-1/2"></div>
          <div className="grid grid-cols-2 gap-4">
            <div className="h-20 bg-slate-100 rounded"></div>
            <div className="h-20 bg-slate-100 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <div className="text-center py-8">
          <p className="text-sm text-slate-600 mb-4">
            {error || (isAr ? "لا يوجد اشتراك نشط" : "No active subscription")}
          </p>
          <Link
            href={`/${lang}/pricing`}
            className="inline-block rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover"
          >
            {isAr ? "اختر خطة" : "Choose a plan"}
          </Link>
        </div>
      </div>
    );
  }

  const { subscription, user } = data;

  // Format tier name
  const tierNames: Record<string, { en: string; ar: string }> = {
    tier1: { en: "Starter", ar: "المبتدئ" },
    tier2: { en: "Professional", ar: "المحترف" },
    tier3: { en: "Business", ar: "الأعمال" },
    tier4: { en: "Enterprise", ar: "المؤسسات" },
    tier5: { en: "Ultimate", ar: "النهائي" },
  };

  const tierName =
    tierNames[subscription.tierId]?.[lang] || subscription.tierId;

  // Format status
  const statusLabels: Record<
    string,
    { en: string; ar: string; color: string }
  > = {
    active: { en: "Active", ar: "نشط", color: "emerald" },
    trialing: { en: "Trial Period", ar: "فترة تجريبية", color: "blue" },
    past_due: { en: "Past Due", ar: "متأخر", color: "orange" },
    canceled: { en: "Canceled", ar: "ملغى", color: "slate" },
    unpaid: { en: "Unpaid", ar: "غير مدفوع", color: "red" },
  };

  const status = statusLabels[subscription.status] || {
    en: subscription.status,
    ar: subscription.status,
    color: "slate",
  };

  // Static color variants mapping for Tailwind JIT compiler
  const statusColorVariants: Record<string, string> = {
    emerald: "bg-emerald-100 text-emerald-700",
    blue: "bg-blue-100 text-blue-700",
    orange: "bg-orange-100 text-orange-700",
    slate: "bg-slate-100 text-slate-700",
    red: "bg-red-100 text-red-700",
    green: "bg-green-100 text-green-700",
    purple: "bg-purple-100 text-purple-700",
    yellow: "bg-yellow-100 text-yellow-700",
    amber: "bg-amber-100 text-amber-700",
    rose: "bg-rose-100 text-rose-700",
  };

  return (
    <div className="space-y-4">
      {/* Main Subscription Card */}
      <div className="rounded-xl bg-gradient-to-br from-brand-green to-emerald-600 p-6 text-white shadow-lg">
        <div className="flex items-start justify-between">
          <div>
            <p className="text-xs font-medium text-emerald-100">
              {isAr ? "خطتك الحالية" : "Current Plan"}
            </p>
            <h2 className="mt-1 text-2xl font-bold">{tierName}</h2>
            <p className="mt-1 text-sm text-emerald-100">
              {subscription.billingPeriod === "monthly"
                ? isAr
                  ? "فوترة شهرية"
                  : "Billed Monthly"
                : isAr
                  ? "فوترة سنوية"
                  : "Billed Yearly"}
            </p>
          </div>
          <span
            className={`rounded-full px-3 py-1 text-xs font-semibold ${statusColorVariants[status.color] || statusColorVariants.slate}`}
          >
            {isAr ? status.ar : status.en}
          </span>
        </div>

        <div className="mt-6 grid grid-cols-2 gap-4">
          <div>
            <p className="text-xs text-emerald-100">
              {subscription.trialEndsAt
                ? isAr
                  ? "تنتهي الفترة التجريبية"
                  : "Trial ends"
                : isAr
                  ? "التجديد التالي"
                  : "Next billing"}
            </p>
            <p className="mt-1 text-sm font-semibold">
              {new Date(
                subscription.trialEndsAt || subscription.currentPeriodEnd,
              ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                month: "short",
                day: "numeric",
                year: "numeric",
              })}
            </p>
          </div>
          {subscription.lastPaymentDate && (
            <div>
              <p className="text-xs text-emerald-100">
                {isAr ? "آخر دفعة" : "Last payment"}
              </p>
              <p className="mt-1 text-sm font-semibold">
                {new Date(subscription.lastPaymentDate).toLocaleDateString(
                  isAr ? "ar-SA" : "en-US",
                  { month: "short", day: "numeric" },
                )}
              </p>
            </div>
          )}
        </div>

        {subscription.cancelAtPeriodEnd && (
          <div className="mt-4 rounded-lg bg-orange-500/20 border border-orange-300/30 px-3 py-2">
            <p className="text-xs font-medium">
              ⚠️{" "}
              {isAr
                ? `سيتم إلغاء الاشتراك في ${new Date(subscription.currentPeriodEnd).toLocaleDateString(isAr ? "ar-SA" : "en-US")}`
                : `Subscription will cancel on ${new Date(subscription.currentPeriodEnd).toLocaleDateString("en-US")}`}
            </p>
          </div>
        )}
      </div>

      {/* Payment Method & Setup Fee */}
      <div className="grid gap-4 md:grid-cols-2">
        {/* Payment Method */}
        <div className="rounded-xl bg-white p-5 shadow-sm border border-slate-100">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-semibold text-slate-900">
              {isAr ? "طريقة الدفع" : "Payment Method"}
            </h3>
            <button className="text-xs text-brand-green hover:underline">
              {isAr ? "تحديث" : "Update"}
            </button>
          </div>

          {subscription.paymentMethod ? (
            <div className="mt-4 flex items-center gap-3 rounded-lg bg-slate-50 p-3">
              <div className="flex h-10 w-14 items-center justify-center rounded bg-slate-900 text-white text-xs font-bold uppercase">
                {subscription.paymentMethod.brand === "visa" && "VISA"}
                {subscription.paymentMethod.brand === "mastercard" && "MC"}
                {subscription.paymentMethod.brand === "amex" && "AMEX"}
                {!["visa", "mastercard", "amex"].includes(
                  subscription.paymentMethod.brand,
                ) && subscription.paymentMethod.brand.slice(0, 4)}
              </div>
              <div>
                <p className="text-xs font-medium text-slate-900">
                  {subscription.paymentMethod.brand.charAt(0).toUpperCase() +
                    subscription.paymentMethod.brand.slice(1)}{" "}
                  •••• {subscription.paymentMethod.lastFour}
                </p>
                <p className="text-[10px] text-slate-500">
                  {isAr ? "طريقة الدفع الافتراضية" : "Default payment method"}
                </p>
              </div>
            </div>
          ) : (
            <div className="mt-4 rounded-lg border border-dashed border-slate-200 p-4 text-center">
              <p className="text-xs text-slate-500">
                {isAr ? "لم يتم تعيين طريقة دفع" : "No payment method set"}
              </p>
            </div>
          )}
        </div>

        {/* Setup Fee */}
        <div className="rounded-xl bg-white p-5 shadow-sm border border-slate-100">
          <h3 className="text-sm font-semibold text-slate-900">
            {isAr ? "رسوم الإعداد" : "Setup Fee"}
          </h3>

          {subscription.setupFeePaid ? (
            <div className="mt-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-600">
                  {isAr ? "المبلغ" : "Amount"}
                </span>
                <span className="text-sm font-semibold text-slate-900">
                  {subscription.setupFeeAmount
                    ? `${(subscription.setupFeeAmount / 100).toFixed(2)} QAR`
                    : isAr
                      ? "غير محدد"
                      : "Not specified"}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-xs text-slate-600">
                  {isAr ? "تاريخ الدفع" : "Paid on"}
                </span>
                <span className="text-xs font-medium text-slate-900">
                  {subscription.setupFeePaidAt
                    ? new Date(subscription.setupFeePaidAt).toLocaleDateString(
                        isAr ? "ar-SA" : "en-US",
                        { month: "short", day: "numeric", year: "numeric" },
                      )
                    : "-"}
                </span>
              </div>
              <div className="rounded-lg bg-emerald-50 px-3 py-2 flex items-center gap-2">
                <span className="text-emerald-600">✓</span>
                <span className="text-xs font-medium text-emerald-700">
                  {isAr ? "تم الدفع" : "Paid"}
                </span>
              </div>
            </div>
          ) : (
            <div className="mt-4 rounded-lg bg-yellow-50 border border-yellow-200 px-3 py-2">
              <p className="text-xs text-yellow-700">
                {isAr
                  ? "رسوم الإعداد لم يتم دفعها بعد"
                  : "Setup fee not paid yet"}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() => setShowPlanChangeModal(true)}
          className="rounded-lg bg-brand-green px-4 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
        >
          {isAr ? "🔄 تغيير الخطة" : "🔄 Change Plan"}
        </button>
        {!hideFullBillingLink && (
          <Link
            href={`/${lang}/dashboard/billing`}
            className="rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-medium text-slate-700 hover:border-brand-green hover:text-brand-green transition-colors"
          >
            {isAr ? "📋 سجل الفواتير الكامل" : "📋 Full Billing History"}
          </Link>
        )}
        <button
          className="rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-medium text-slate-700 hover:border-slate-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          onClick={handleBillingPortal}
          disabled={portalLoading}
        >
          {portalLoading ? (
            <span className="flex items-center gap-2">
              <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                  fill="none"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
              {isAr ? "جاري التحميل..." : "Loading..."}
            </span>
          ) : isAr ? (
            "🔗 بوابة الفواتير"
          ) : (
            "🔗 Billing Portal"
          )}
        </button>
      </div>

      {/* Plan Change Modal */}
      <PlanChangeModal
        lang={lang}
        isOpen={showPlanChangeModal}
        onClose={() => setShowPlanChangeModal(false)}
        currentTierId={subscription.tierId as TierId}
        currentBillingPeriod={subscription.billingPeriod as BillingPeriod}
        currentPeriodEnd={subscription.currentPeriodEnd}
        onSuccess={() => {
          setShowPlanChangeModal(false);
          // Refresh subscription data after plan change
          fetchSubscription();
        }}
      />
    </div>
  );
}
