/**
 * Billing Tab Component - FIXED VERSION
 * Complete billing management: current plan, upgrade, invoices
 * Uses /api/subscription/details directly (proven to work)
 */

"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import type { Lang } from "@/lib/config";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import { convertPrice, getDaysUntilBilling } from "@/lib/utils/pricing-helpers";
import type { Currency, TierId } from "@/lib/types/pricing";
import { PlanUpgradeModal } from "@/app/[lang]/dashboard/components/PlanUpgradeModal";

interface BillingTabProps {
  lang: Lang;
  onUnsavedChanges?: (hasChanges: boolean) => void;
  onClose?: () => void;
}

interface SubscriptionData {
  id: string;
  tierId: string;
  status: string;
  billingPeriod: "monthly" | "yearly";
  currentPeriodEnd: string;
  trialEndsAt: string | null;
  setupFeePaid: boolean;
  setupFeeAmount: number | null;
  setupFeePaidAt: string | null;
  stripeCustomerId: string | null;
  stripeSubscriptionId: string | null;
  paymentMethod?: {
    brand: string;
    lastFour: string;
  } | null;
}

interface Invoice {
  id: string;
  number: string | null;
  date: string;
  amount: number;
  currency: string;
  status: string;
  pdfUrl: string | null;
  hostedUrl: string | null;
  description: string;
}

export default function BillingTabFixed({
  lang,
  onUnsavedChanges,
  onClose,
}: BillingTabProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [subscription, setSubscription] = useState<SubscriptionData | null>(
    null,
  );
  const [currency, setCurrency] = useState<Currency>("QAR");
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [showUpgradeModal, setShowUpgradeModal] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load subscription
  useEffect(() => {
    let mounted = true;

    async function load() {
      try {
        console.log("🔍 [BillingTab] Starting load...");

        const res = await fetch("/api/subscription/details");
        console.log("📡 [BillingTab] Response:", res.status, res.statusText);

        if (!res.ok) {
          const errorData = await res
            .json()
            .catch(() => ({ error: "Unknown error" }));
          console.error("❌ [BillingTab] API error:", errorData);

          if (res.status === 404) {
            // No subscription found - this is OK
            if (mounted) {
              setSubscription(null);
              setError(null);
            }
          } else {
            if (mounted) {
              setError(errorData.error || "Failed to load subscription");
            }
          }
          return;
        }

        const data = await res.json();
        console.log("📦 [BillingTab] Data received:", {
          hasSubscription: !!data.subscription,
          tier: data.subscription?.tierId,
          status: data.subscription?.status,
        });

        if (mounted && data.subscription) {
          console.log("✅ [BillingTab] Setting subscription state");
          setSubscription(data.subscription);

          // Set currency from billing history
          const curr =
            data.billingHistory?.[0]?.currency?.toUpperCase() as Currency;
          setCurrency(curr || "QAR");

          console.log(
            "💾 [BillingTab] State updated:",
            data.subscription.tierId,
          );
        }
      } catch (err) {
        console.error("❌ [BillingTab] Fetch error:", err);
        if (mounted) {
          setError(err instanceof Error ? err.message : "Network error");
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    }

    load();

    return () => {
      mounted = false;
    };
  }, []);

  // Load invoices
  useEffect(() => {
    fetch("/api/billing/invoices?limit=20")
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data?.invoices) {
          setInvoices(data.invoices);
        }
      })
      .catch((err) => console.error("Failed to load invoices:", err));
  }, []);

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-slate-200 rounded w-1/3"></div>
          <div className="h-48 bg-slate-200 rounded"></div>
        </div>
      </div>
    );
  }

  // Get tier info
  const tierInfo = subscription
    ? PRICING_TIERS.find((t) => t.id === subscription.tierId)
    : null;
  const tierName = tierInfo ? (isAr ? tierInfo.nameAr : tierInfo.nameEn) : null;
  const daysRemaining = subscription?.currentPeriodEnd
    ? getDaysUntilBilling(new Date(subscription.currentPeriodEnd))
    : 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-lg font-semibold text-slate-900">
          {isAr ? "الفوترة والاشتراك" : "Billing & Subscription"}
        </h2>
        <p className="text-sm text-slate-600 mt-1">
          {isAr
            ? "إدارة خطتك، طرق الدفع، والفواتير"
            : "Manage your plan, payment methods, and invoices"}
        </p>
      </div>

      {/* Error Display */}
      {error && (
        <div className="rounded-lg bg-red-50 border border-red-200 p-4">
          <p className="text-sm text-red-800">❌ {error}</p>
        </div>
      )}

      {/* Current Plan */}
      {subscription ? (
        <div className="rounded-xl bg-gradient-to-br from-emerald-50 to-sky-50 p-6 border-2 border-emerald-200">
          {/* Status Badge */}
          <div className="mb-3">
            {subscription.status === "trialing" ? (
              <span className="inline-flex items-center gap-2 rounded-full bg-violet-100 px-3 py-1.5 text-xs font-semibold text-violet-700">
                🎯 {isAr ? "في الفترة التجريبية" : "In Trial Period"}
              </span>
            ) : (
              <span className="inline-flex items-center gap-2 rounded-full bg-emerald-100 px-3 py-1.5 text-xs font-semibold text-emerald-700">
                ✓ {isAr ? "اشتراك نشط" : "Active Subscription"}
              </span>
            )}
          </div>

          {/* Plan Name */}
          <h3 className="text-2xl font-bold text-slate-900 mb-2">
            {tierName || subscription.tierId}
          </h3>
          <p className="text-sm text-slate-600 mb-4">
            {subscription.billingPeriod === "monthly"
              ? isAr
                ? "فوترة شهرية"
                : "Monthly billing"
              : isAr
                ? "فوترة سنوية"
                : "Yearly billing"}
          </p>

          {/* Trial Notice */}
          {subscription.status === "trialing" && subscription.trialEndsAt && (
            <div className="mb-4 rounded-lg bg-violet-50 border-2 border-violet-200 p-4">
              <p className="text-sm font-semibold text-violet-900 mb-1">
                🎁 {isAr ? "تجربة مجانية نشطة" : "Free Trial Active"}
              </p>
              <p className="text-sm text-violet-700">
                {isAr ? "تنتهي في:" : "Ends on:"}{" "}
                {new Date(subscription.trialEndsAt).toLocaleDateString(
                  isAr ? "ar-SA" : "en-US",
                  { month: "long", day: "numeric", year: "numeric" },
                )}
              </p>
              <p className="text-xs text-violet-600 mt-2">
                💡{" "}
                {isAr
                  ? "لن يتم تحصيل أي رسوم حتى نهاية الفترة التجريبية"
                  : "No charges until trial ends"}
              </p>
            </div>
          )}

          {/* Plan Details Grid */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
            <div className="rounded-lg bg-white/80 p-3">
              <p className="text-xs text-slate-600">
                {isAr ? "الحالة" : "Status"}
              </p>
              <p
                className={`text-sm font-semibold ${
                  subscription.status === "trialing"
                    ? "text-violet-600"
                    : subscription.status === "active"
                      ? "text-emerald-600"
                      : "text-amber-600"
                }`}
              >
                {subscription.status === "trialing"
                  ? isAr
                    ? "تجريبي"
                    : "Trial"
                  : subscription.status === "active"
                    ? isAr
                      ? "نشط"
                      : "Active"
                    : subscription.status}
              </p>
            </div>
            <div className="rounded-lg bg-white/80 p-3">
              <p className="text-xs text-slate-600">
                {isAr ? "السعر الشهري" : "Monthly Price"}
              </p>
              <p className="text-sm font-semibold text-slate-900">
                {currency}{" "}
                {tierInfo
                  ? convertPrice(tierInfo.priceGBP, currency).toLocaleString()
                  : "-"}
              </p>
            </div>
            <div className="rounded-lg bg-white/80 p-3">
              <p className="text-xs text-slate-600">
                {subscription.status === "trialing"
                  ? isAr
                    ? "نهاية التجربة"
                    : "Trial Ends"
                  : isAr
                    ? "التجديد"
                    : "Renews"}
              </p>
              <p className="text-sm font-semibold text-slate-900">
                {new Date(
                  subscription.status === "trialing" && subscription.trialEndsAt
                    ? subscription.trialEndsAt
                    : subscription.currentPeriodEnd,
                ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                  month: "short",
                  day: "numeric",
                })}
              </p>
            </div>
            <div className="rounded-lg bg-white/80 p-3">
              <p className="text-xs text-slate-600">
                {isAr ? "متبقي" : "Remaining"}
              </p>
              <p className="text-sm font-semibold text-violet-600">
                {daysRemaining} {isAr ? "يوم" : "days"}
              </p>
            </div>
          </div>

          {/* Payment Status */}
          {subscription.status === "trialing" && (
            <div className="rounded-lg bg-emerald-50 border border-emerald-200 p-3 mb-4">
              <p className="text-xs font-semibold text-emerald-900 mb-1">
                ✓ {isAr ? "تم الدفع والتفعيل" : "Payment Completed & Active"}
              </p>
              {subscription.setupFeePaid && (
                <p className="text-xs text-emerald-700">
                  ✓ {isAr ? "رسوم الإعداد مدفوعة" : "Setup fee paid"}
                  {subscription.setupFeeAmount &&
                    ` (${(subscription.setupFeeAmount / 100).toFixed(2)} ${currency})`}
                </p>
              )}
              {subscription.paymentMethod && (
                <p className="text-xs text-emerald-700">
                  ✓ {isAr ? "طريقة الدفع:" : "Payment method:"}{" "}
                  {subscription.paymentMethod.brand} ****
                  {subscription.paymentMethod.lastFour}
                </p>
              )}
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-3">
            <button
              onClick={() => setShowUpgradeModal(true)}
              className="flex-1 rounded-lg bg-brand-green px-4 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover"
            >
              ⬆️ {isAr ? "ترقية الخطة" : "Upgrade Plan"}
            </button>
            <Link
              href={`/${lang}/pricing`}
              className="rounded-lg border-2 border-slate-300 px-4 py-2.5 text-sm font-medium text-slate-700 hover:border-brand-green hover:bg-slate-50"
            >
              {isAr ? "عرض جميع الخطط" : "View All Plans"}
            </Link>
          </div>
        </div>
      ) : (
        <div className="rounded-xl bg-amber-50 border-2 border-amber-200 p-6 text-center">
          <div className="text-5xl mb-3">📦</div>
          <h3 className="text-lg font-semibold text-slate-900 mb-2">
            {isAr ? "لا يوجد اشتراك نشط" : "No Active Subscription"}
          </h3>
          <p className="text-sm text-slate-600 mb-4">
            {isAr
              ? "اختر الخطة المثالية لعملك"
              : "Choose the perfect plan for your business"}
          </p>
          <Link
            href={`/${lang}/pricing`}
            className="inline-flex items-center gap-2 rounded-lg bg-brand-green px-6 py-3 text-sm font-semibold text-white hover:bg-brand-greenHover"
          >
            {isAr ? "اختر خطة" : "Choose a Plan"} →
          </Link>
        </div>
      )}

      {/* Subscription Summary */}
      {subscription && (
        <div className="rounded-xl bg-white p-5 border border-slate-200">
          <h3 className="text-base font-semibold text-slate-900 mb-4">
            {isAr ? "ملخص الاشتراك" : "Subscription Summary"}
          </h3>
          <div className="space-y-2">
            <div className="flex justify-between items-center p-3 rounded-lg bg-emerald-50">
              <span className="text-sm text-slate-700">
                {isAr ? "حالة الدفع" : "Payment Status"}
              </span>
              <span className="text-sm font-semibold text-emerald-700">
                ✓ {isAr ? "مدفوع" : "Paid"}
              </span>
            </div>
            <div className="flex justify-between items-center p-3 rounded-lg bg-slate-50">
              <span className="text-sm text-slate-700">
                {isAr ? "نوع الاشتراك" : "Subscription Type"}
              </span>
              <span className="text-sm font-semibold text-slate-900">
                {subscription.status === "trialing"
                  ? isAr
                    ? "🎁 تجربة مجانية"
                    : "🎁 Free Trial"
                  : isAr
                    ? "💎 اشتراك كامل"
                    : "💎 Full Subscription"}
              </span>
            </div>
            {subscription.setupFeePaid && (
              <div className="flex justify-between items-center p-3 rounded-lg bg-blue-50">
                <span className="text-sm text-slate-700">
                  {isAr ? "رسوم الإعداد" : "Setup Fee"}
                </span>
                <span className="text-sm font-semibold text-blue-700">
                  ✓ {isAr ? "مدفوعة" : "Paid"}
                  {subscription.setupFeeAmount &&
                    ` (${(subscription.setupFeeAmount / 100).toFixed(2)} ${currency})`}
                </span>
              </div>
            )}
            <div className="flex justify-between items-center p-3 rounded-lg bg-violet-50">
              <span className="text-sm text-slate-700">
                {subscription.status === "trialing"
                  ? isAr
                    ? "أول دفعة"
                    : "First Charge"
                  : isAr
                    ? "الدفعة القادمة"
                    : "Next Payment"}
              </span>
              <span className="text-sm font-semibold text-violet-700">
                {new Date(
                  subscription.status === "trialing" && subscription.trialEndsAt
                    ? subscription.trialEndsAt
                    : subscription.currentPeriodEnd,
                ).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                  month: "short",
                  day: "numeric",
                  year: "numeric",
                })}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Invoices */}
      <div>
        <h3 className="text-base font-semibold text-slate-900 mb-3">
          {isAr ? "الفواتير" : "Invoices"}
        </h3>

        {invoices.length === 0 ? (
          <div className="rounded-lg bg-slate-50 border-2 border-dashed border-slate-200 p-8 text-center">
            <div className="text-4xl mb-2">🧾</div>
            <p className="text-sm text-slate-600">
              {isAr ? "لا توجد فواتير بعد" : "No invoices yet"}
            </p>
          </div>
        ) : (
          <div className="rounded-lg bg-white border border-slate-200 overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-slate-200 bg-slate-50">
                  <th className="px-4 py-3 text-left font-semibold text-slate-700">
                    {isAr ? "الفاتورة" : "Invoice"}
                  </th>
                  <th className="px-4 py-3 text-left font-semibold text-slate-700">
                    {isAr ? "التاريخ" : "Date"}
                  </th>
                  <th className="px-4 py-3 text-left font-semibold text-slate-700">
                    {isAr ? "الوصف" : "Description"}
                  </th>
                  <th className="px-4 py-3 text-right font-semibold text-slate-700">
                    {isAr ? "المبلغ" : "Amount"}
                  </th>
                  <th className="px-4 py-3 text-center font-semibold text-slate-700">
                    {isAr ? "الحالة" : "Status"}
                  </th>
                  <th className="px-4 py-3 text-center font-semibold text-slate-700">
                    {isAr ? "الإجراء" : "Action"}
                  </th>
                </tr>
              </thead>
              <tbody>
                {invoices.map((inv) => (
                  <tr
                    key={inv.id}
                    className="border-b border-slate-100 hover:bg-slate-50"
                  >
                    <td className="px-4 py-3 text-slate-900 font-medium">
                      {inv.number || inv.id.substring(0, 8)}
                    </td>
                    <td className="px-4 py-3 text-slate-600">
                      {new Date(inv.date).toLocaleDateString(
                        isAr ? "ar-SA" : "en-US",
                        { month: "short", day: "numeric", year: "numeric" },
                      )}
                    </td>
                    <td className="px-4 py-3 text-slate-600">
                      {inv.description}
                    </td>
                    <td className="px-4 py-3 text-right font-semibold text-slate-900">
                      {inv.amount.toFixed(2)} {inv.currency}
                    </td>
                    <td className="px-4 py-3 text-center">
                      <span
                        className={`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-semibold ${
                          inv.status === "paid"
                            ? "bg-emerald-100 text-emerald-700"
                            : inv.status === "open"
                              ? "bg-amber-100 text-amber-700"
                              : "bg-slate-100 text-slate-700"
                        }`}
                      >
                        {inv.status === "paid" && "✓"}
                        {inv.status === "paid"
                          ? isAr
                            ? "مدفوع"
                            : "Paid"
                          : inv.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {inv.pdfUrl && (
                        <a
                          href={inv.pdfUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-xs text-brand-green hover:underline font-medium"
                        >
                          {isAr ? "تحميل PDF" : "Download PDF"} ↓
                        </a>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Payment Methods */}
      <div className="rounded-lg bg-slate-50 border border-slate-200 p-5">
        <h3 className="text-base font-semibold text-slate-900 mb-2">
          {isAr ? "طرق الدفع" : "Payment Methods"}
        </h3>
        <p className="text-sm text-slate-600 mb-3">
          {isAr
            ? "يتم إدارة طرق الدفع من خلال Stripe"
            : "Payment methods are managed through Stripe"}
        </p>
        {subscription?.stripeCustomerId && (
          <a
            href="https://billing.stripe.com/p/login/test_3cs5nvdxVfOu4fu288"
            target="_blank"
            rel="noopener noreferrer"
            className="text-sm text-brand-green hover:underline font-medium"
          >
            {isAr ? "إدارة طرق الدفع" : "Manage Payment Methods"} →
          </a>
        )}
      </div>

      {/* Support */}
      <div className="rounded-lg bg-blue-50 border border-blue-200 p-4">
        <p className="text-sm text-blue-900">
          💡{" "}
          {isAr ? "لديك أسئلة حول الفوترة؟" : "Have questions about billing?"}
        </p>
        <Link
          href={`/${lang}/contact`}
          className="inline-flex items-center gap-2 mt-2 text-sm text-blue-700 hover:underline font-medium"
        >
          {isAr ? "اتصل بالدعم" : "Contact Support"} →
        </Link>
      </div>

      {/* Upgrade Modal */}
      {subscription && (
        <PlanUpgradeModal
          lang={lang}
          isOpen={showUpgradeModal}
          onClose={() => setShowUpgradeModal(false)}
          subscriptionData={{
            subscription: subscription as any,
            user: { id: "", email: "", name: null, companyName: null },
            billingHistory: [],
          }}
          currency={currency}
          billingPeriod={subscription.billingPeriod}
          onSuccess={() => window.location.reload()}
        />
      )}
    </div>
  );
}
