/**
 * Billing History Component
 * Displays payment history table with all billing events and invoice download
 */

"use client";

import { useEffect, useState } from "react";
import type { Lang } from "@/lib/config";

interface BillingEvent {
  id: string;
  event: string;
  amount: number;
  currency: string;
  createdAt: string;
  metadata?: {
    tier_id?: string;
    payment_method_brand?: string;
    payment_method_last_four?: string;
    payment_type?: string;
    from_tier?: string;
    to_tier?: string;
    invoice_number?: string;
    billing_reason?: string;
    [key: string]: any;
  };
  invoiceId?: string | null;
  invoiceUrl?: string | null;
  invoicePdf?: string | null;
  invoiceStatus?: string | null;
  invoiceNumber?: string | null;
}

interface BillingHistoryData {
  billingHistory: BillingEvent[];
  source?: "local" | "stripe" | "combined";
  hasMore?: boolean;
}

interface BillingHistoryProps {
  lang: Lang;
  limit?: number;
  showViewAll?: boolean;
}

export default function BillingHistory({
  lang,
  limit,
  showViewAll = true,
}: BillingHistoryProps) {
  const [data, setData] = useState<BillingHistoryData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloadingInvoice, setDownloadingInvoice] = useState<string | null>(
    null,
  );

  const isAr = lang === "ar";

  useEffect(() => {
    async function fetchBillingHistory() {
      try {
        // Use the new billing history API with Stripe fallback
        const response = await fetch(
          `/api/billing/history?limit=${limit || 20}&include_invoices=true`,
        );

        if (!response.ok) {
          if (response.status === 404) {
            setError(isAr ? "لا يوجد سجل فواتير" : "No billing history");
          } else if (response.status === 401) {
            setError(isAr ? "يرجى تسجيل الدخول" : "Please log in");
          } else {
            throw new Error("Failed to fetch billing history");
          }
          return;
        }

        const result = await response.json();
        setData({
          billingHistory: result.billingHistory || [],
          source: result.source,
          hasMore: result.hasMore,
        });
      } catch (err) {
        console.error("Error fetching billing history:", err);
        setError(
          isAr ? "فشل تحميل سجل الفواتير" : "Failed to load billing history",
        );
      } finally {
        setLoading(false);
      }
    }

    fetchBillingHistory();
  }, [isAr, limit]);

  const handleViewInvoice = (invoiceId: string, invoiceUrl?: string | null) => {
    if (invoiceUrl) {
      window.open(invoiceUrl, "_blank", "noopener,noreferrer");
    } else {
      // Fetch invoice URL via API
      window.open(
        `/api/billing/invoice/${invoiceId}?format=redirect`,
        "_blank",
        "noopener,noreferrer",
      );
    }
  };

  const handleDownloadInvoice = async (
    invoiceId: string,
    invoicePdf?: string | null,
  ) => {
    setDownloadingInvoice(invoiceId);
    try {
      if (invoicePdf) {
        // Direct download from Stripe URL
        const link = document.createElement("a");
        link.href = invoicePdf;
        link.target = "_blank";
        link.rel = "noopener noreferrer";
        link.click();
      } else {
        // Use API to get PDF URL
        const response = await fetch(`/api/billing/invoice/${invoiceId}`);
        if (response.ok) {
          const data = await response.json();
          if (data.invoice?.pdfUrl) {
            const link = document.createElement("a");
            link.href = data.invoice.pdfUrl;
            link.target = "_blank";
            link.rel = "noopener noreferrer";
            link.click();
          }
        }
      }
    } catch (err) {
      console.error("Failed to download invoice:", err);
    } finally {
      setDownloadingInvoice(null);
    }
  };

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <div className="animate-pulse space-y-3">
          <div className="h-4 bg-slate-200 rounded w-1/4"></div>
          <div className="space-y-2">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-12 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">
          <div className="mx-auto w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
            <svg
              className="w-6 h-6 text-slate-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
          </div>
          <p className="text-sm text-slate-600">
            {error ||
              (isAr ? "لا توجد عمليات فواتير" : "No billing events yet")}
          </p>
        </div>
      </div>
    );
  }

  const events = limit
    ? data.billingHistory.slice(0, limit)
    : data.billingHistory;

  // Event labels with icons
  const eventLabels: Record<
    string,
    { en: string; ar: string; icon: string; color: string }
  > = {
    checkout_completed: {
      en: "Checkout Completed",
      ar: "اكتمل الدفع",
      icon: "✅",
      color: "emerald",
    },
    setup_fee_paid: {
      en: "Setup Fee",
      ar: "رسوم الإعداد",
      icon: "💰",
      color: "blue",
    },
    booking_deposit_paid: {
      en: "Appointment Deposit",
      ar: "عربون الموعد",
      icon: "📅",
      color: "teal",
    },
    invoice_paid: {
      en: "Invoice Paid",
      ar: "تم دفع الفاتورة",
      icon: "✓",
      color: "emerald",
    },
    proration_payment: {
      en: "Prorated Payment",
      ar: "دفعة نسبية",
      icon: "📊",
      color: "violet",
    },
    invoice_payment_failed: {
      en: "Payment Failed",
      ar: "فشل الدفع",
      icon: "⚠️",
      color: "red",
    },
    subscription_upgraded: {
      en: "Plan Upgraded",
      ar: "ترقية الخطة",
      icon: "⬆️",
      color: "violet",
    },
    subscription_downgraded: {
      en: "Plan Downgraded",
      ar: "تخفيض الخطة",
      icon: "⬇️",
      color: "orange",
    },
    subscription_cancelled: {
      en: "Subscription Canceled",
      ar: "إلغاء الاشتراك",
      icon: "❌",
      color: "slate",
    },
    billing_period_changed: {
      en: "Billing Period Changed",
      ar: "تغيير دورة الفوترة",
      icon: "🔄",
      color: "sky",
    },
    seats_updated: {
      en: "Seats Updated",
      ar: "تحديث المقاعد",
      icon: "👥",
      color: "indigo",
    },
    charge_refunded: {
      en: "Refund",
      ar: "استرداد",
      icon: "↩️",
      color: "amber",
    },
    refund_synced: {
      en: "Refund Processed",
      ar: "تم الاسترداد",
      icon: "↩️",
      color: "amber",
    },
  };

  return (
    <div className="rounded-xl bg-white shadow-sm border border-slate-100">
      <div className="p-5 border-b border-slate-100">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-sm font-semibold text-slate-900">
              {isAr ? "سجل الفواتير" : "Billing History"}
            </h3>
            <p className="mt-1 text-xs text-slate-500">
              {isAr
                ? `عرض آخر ${events.length} عملية`
                : `Showing last ${events.length} transactions`}
            </p>
          </div>
          {data.source === "stripe" && (
            <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-violet-100 text-[10px] font-medium text-violet-700">
              <svg className="w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
                <path d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.591-7.305z" />
              </svg>
              {isAr ? "من Stripe" : "From Stripe"}
            </span>
          )}
        </div>
      </div>

      {events.length === 0 ? (
        <div className="p-6 text-center">
          <div className="mx-auto w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
            <svg
              className="w-6 h-6 text-slate-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
          </div>
          <p className="text-sm text-slate-500">
            {isAr ? "لا توجد عمليات فواتير بعد" : "No billing events yet"}
          </p>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-xs">
            <thead>
              <tr className="border-b border-slate-100 bg-slate-50">
                <th
                  className={`px-4 py-3 ${isAr ? "text-right" : "text-left"} font-semibold text-slate-600`}
                >
                  {isAr ? "التاريخ" : "Date"}
                </th>
                <th
                  className={`px-4 py-3 ${isAr ? "text-right" : "text-left"} font-semibold text-slate-600`}
                >
                  {isAr ? "الحدث" : "Event"}
                </th>
                <th
                  className={`px-4 py-3 ${isAr ? "text-left" : "text-right"} font-semibold text-slate-600`}
                >
                  {isAr ? "المبلغ" : "Amount"}
                </th>
                <th
                  className={`px-4 py-3 ${isAr ? "text-right" : "text-left"} font-semibold text-slate-600`}
                >
                  {isAr ? "الفاتورة" : "Invoice"}
                </th>
              </tr>
            </thead>
            <tbody>
              {events.map((event) => {
                const eventInfo = eventLabels[event.event] || {
                  en: event.event
                    .replace(/_/g, " ")
                    .replace(/\b\w/g, (c) => c.toUpperCase()),
                  ar: event.event,
                  icon: "•",
                  color: "slate",
                };

                const isNegative = event.amount < 0;
                const displayAmount = Math.abs(event.amount) / 100;
                const hasInvoice =
                  event.invoiceId || event.invoiceUrl || event.invoicePdf;
                const invoiceNumber =
                  event.invoiceNumber || event.metadata?.invoice_number;

                return (
                  <tr
                    key={event.id}
                    className="border-b border-slate-50 hover:bg-slate-50/50"
                  >
                    <td
                      className={`px-4 py-3 text-slate-700 ${isAr ? "text-right" : ""}`}
                    >
                      {new Date(event.createdAt).toLocaleDateString(
                        isAr ? "ar-SA" : "en-US",
                        { month: "short", day: "numeric", year: "numeric" },
                      )}
                      <br />
                      <span className="text-[10px] text-slate-500">
                        {new Date(event.createdAt).toLocaleTimeString(
                          isAr ? "ar-SA" : "en-US",
                          { hour: "2-digit", minute: "2-digit" },
                        )}
                      </span>
                    </td>
                    <td className={`px-4 py-3 ${isAr ? "text-right" : ""}`}>
                      <div
                        className={`flex items-center gap-2 ${isAr ? "flex-row-reverse" : ""}`}
                      >
                        <span>{eventInfo.icon}</span>
                        <span className="font-medium text-slate-900">
                          {isAr ? eventInfo.ar : eventInfo.en}
                        </span>
                      </div>
                      {event.metadata?.from_tier && event.metadata?.to_tier && (
                        <span className="text-[10px] text-slate-500">
                          {event.metadata.from_tier} → {event.metadata.to_tier}
                        </span>
                      )}
                      {event.metadata?.seat_quantity && (
                        <span className="text-[10px] text-slate-500">
                          {isAr
                            ? `${event.metadata.seat_quantity} مقاعد`
                            : `${event.metadata.seat_quantity} seats`}
                        </span>
                      )}
                    </td>
                    <td
                      className={`px-4 py-3 ${isAr ? "text-left" : "text-right"} font-semibold ${
                        isNegative ? "text-emerald-600" : "text-slate-900"
                      }`}
                    >
                      {isNegative && "+ "}
                      {displayAmount.toFixed(2)} {event.currency.toUpperCase()}
                      {isNegative && (
                        <span className="block text-[10px] text-emerald-600 font-normal">
                          {isAr ? "رصيد" : "Credit"}
                        </span>
                      )}
                    </td>
                    <td className={`px-4 py-3 ${isAr ? "text-right" : ""}`}>
                      {hasInvoice ? (
                        <div className="flex flex-col gap-1">
                          {invoiceNumber && (
                            <span className="text-[10px] text-slate-500 font-mono">
                              #{invoiceNumber}
                            </span>
                          )}
                          <div
                            className={`flex gap-1 ${isAr ? "flex-row-reverse" : ""}`}
                          >
                            <button
                              onClick={() =>
                                handleViewInvoice(
                                  event.invoiceId!,
                                  event.invoiceUrl,
                                )
                              }
                              className="inline-flex items-center gap-1 px-2 py-1 rounded bg-slate-100 text-slate-700 hover:bg-slate-200 transition-colors text-[10px] font-medium"
                              title={isAr ? "عرض الفاتورة" : "View Invoice"}
                            >
                              <svg
                                className="w-3 h-3"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                                />
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                                />
                              </svg>
                              {isAr ? "عرض" : "View"}
                            </button>
                            <button
                              onClick={() =>
                                handleDownloadInvoice(
                                  event.invoiceId!,
                                  event.invoicePdf,
                                )
                              }
                              disabled={downloadingInvoice === event.invoiceId}
                              className="inline-flex items-center gap-1 px-2 py-1 rounded bg-emerald-100 text-emerald-700 hover:bg-emerald-200 transition-colors text-[10px] font-medium disabled:opacity-50"
                              title={isAr ? "تحميل PDF" : "Download PDF"}
                            >
                              {downloadingInvoice === event.invoiceId ? (
                                <svg
                                  className="w-3 h-3 animate-spin"
                                  fill="none"
                                  viewBox="0 0 24 24"
                                >
                                  <circle
                                    className="opacity-25"
                                    cx="12"
                                    cy="12"
                                    r="10"
                                    stroke="currentColor"
                                    strokeWidth="4"
                                  ></circle>
                                  <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"
                                  ></path>
                                </svg>
                              ) : (
                                <svg
                                  className="w-3 h-3"
                                  fill="none"
                                  viewBox="0 0 24 24"
                                  stroke="currentColor"
                                >
                                  <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                                  />
                                </svg>
                              )}
                              PDF
                            </button>
                          </div>
                        </div>
                      ) : (
                        <span className="text-[10px] text-slate-400">
                          {event.metadata?.payment_method_brand &&
                          event.metadata?.payment_method_last_four ? (
                            <span className="flex items-center gap-1">
                              <span className="uppercase">
                                {event.metadata.payment_method_brand}
                              </span>
                              <span>
                                ••••{event.metadata.payment_method_last_four}
                              </span>
                            </span>
                          ) : isAr ? (
                            "-"
                          ) : (
                            "-"
                          )}
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* View All Link */}
      {showViewAll && data.hasMore && events.length > 0 && (
        <div className="p-4 border-t border-slate-100 text-center">
          <a
            href={`/${lang}/dashboard/billing`}
            className="text-xs font-medium text-emerald-600 hover:text-emerald-700"
          >
            {isAr ? "عرض جميع الفواتير →" : "View all invoices →"}
          </a>
        </div>
      )}
    </div>
  );
}
