/**
 * Invoices List Component
 * Displays all Stripe invoices with download and view options
 */

"use client";

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

interface Invoice {
  id: string;
  number: string | null;
  status: string | null;
  amount: number;
  currency: string;
  description: string;
  createdAt: string;
  dueDate: string | null;
  paidAt: string | null;
  hostedInvoiceUrl: string | null;
  invoicePdf: string | null;
  periodStart: string | null;
  periodEnd: string | null;
  billingReason: string | null;
  subtotal: number;
  tax: number;
  total: number;
  amountPaid: number;
  amountRemaining: number;
  lineItems: Array<{
    id: string;
    description: string | null;
    amount: number;
    quantity: number | null;
  }>;
}

interface InvoicesListProps {
  lang: Lang;
  limit?: number;
}

export default function InvoicesList({ lang, limit = 50 }: InvoicesListProps) {
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [expandedInvoice, setExpandedInvoice] = useState<string | null>(null);

  const isAr = lang === "ar";

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

  const fetchInvoices = async (startingAfter?: string) => {
    try {
      if (startingAfter) {
        setLoadingMore(true);
      } else {
        setLoading(true);
      }

      const url = new URL("/api/stripe/invoices", window.location.origin);
      url.searchParams.set("limit", String(limit));
      if (startingAfter) {
        url.searchParams.set("starting_after", startingAfter);
      }

      const response = await fetch(url.toString());

      if (!response.ok) {
        throw new Error("Failed to fetch invoices");
      }

      const data = await response.json();

      if (startingAfter) {
        setInvoices((prev) => [...prev, ...data.invoices]);
      } else {
        setInvoices(data.invoices);
      }
      setHasMore(data.hasMore);
    } catch (err) {
      console.error("Error fetching invoices:", err);
      setError(isAr ? "فشل تحميل الفواتير" : "Failed to load invoices");
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  };

  const loadMore = () => {
    if (invoices.length > 0) {
      fetchInvoices(invoices[invoices.length - 1].id);
    }
  };

  const formatCurrency = (amount: number, currency: string) => {
    return new Intl.NumberFormat(isAr ? "ar-QA" : "en-QA", {
      style: "currency",
      currency: currency.toUpperCase(),
      minimumFractionDigits: 2,
    }).format(amount / 100);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString(isAr ? "ar-SA" : "en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const getStatusBadge = (status: string | null) => {
    const statusConfig: Record<
      string,
      { bg: string; text: string; label: { en: string; ar: string } }
    > = {
      paid: {
        bg: "bg-emerald-100",
        text: "text-emerald-700",
        label: { en: "Paid", ar: "مدفوع" },
      },
      open: {
        bg: "bg-amber-100",
        text: "text-amber-700",
        label: { en: "Open", ar: "مفتوح" },
      },
      draft: {
        bg: "bg-slate-100",
        text: "text-slate-700",
        label: { en: "Draft", ar: "مسودة" },
      },
      void: {
        bg: "bg-red-100",
        text: "text-red-700",
        label: { en: "Void", ar: "ملغي" },
      },
      uncollectible: {
        bg: "bg-red-100",
        text: "text-red-700",
        label: { en: "Uncollectible", ar: "غير قابل للتحصيل" },
      },
    };

    const config = statusConfig[status || "draft"] || statusConfig.draft;

    return (
      <span
        className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${config.bg} ${config.text}`}
      >
        {isAr ? config.label.ar : config.label.en}
      </span>
    );
  };

  const getBillingReasonLabel = (reason: string | null) => {
    const reasons: Record<string, { en: string; ar: string }> = {
      subscription_create: { en: "New subscription", ar: "اشتراك جديد" },
      subscription_cycle: { en: "Renewal", ar: "تجديد" },
      subscription_update: { en: "Plan change", ar: "تغيير الخطة" },
      subscription_threshold: { en: "Usage threshold", ar: "حد الاستخدام" },
      manual: { en: "Manual", ar: "يدوي" },
    };

    const label = reasons[reason || ""] || {
      en: reason || "Invoice",
      ar: reason || "فاتورة",
    };
    return isAr ? label.ar : label.en;
  };

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-100">
        <div className="animate-pulse space-y-4">
          <div className="h-6 bg-slate-200 rounded w-1/4"></div>
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-20 bg-slate-100 rounded-lg"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-100">
        <div className="text-center py-8">
          <div className="mx-auto w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mb-3">
            <svg
              className="w-6 h-6 text-red-500"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <p className="text-sm text-slate-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="rounded-xl bg-white shadow-sm border border-slate-100">
      {/* Header */}
      <div className="p-5 border-b border-slate-100">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-slate-900">
              {isAr ? "الفواتير" : "Invoices"}
            </h3>
            <p className="mt-1 text-sm text-slate-500">
              {isAr
                ? `${invoices.length} فاتورة من Stripe`
                : `${invoices.length} invoices from Stripe`}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <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>
              Stripe
            </span>
          </div>
        </div>
      </div>

      {/* Invoice List */}
      {invoices.length === 0 ? (
        <div className="p-8 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 invoices yet"}
          </p>
        </div>
      ) : (
        <div className="divide-y divide-slate-100">
          {invoices.map((invoice) => (
            <div
              key={invoice.id}
              className="hover:bg-slate-50/50 transition-colors"
            >
              {/* Main Invoice Row */}
              <div
                className="p-4 cursor-pointer"
                onClick={() =>
                  setExpandedInvoice(
                    expandedInvoice === invoice.id ? null : invoice.id,
                  )
                }
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    {/* Invoice Icon */}
                    <div
                      className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                        invoice.status === "paid"
                          ? "bg-emerald-100"
                          : "bg-slate-100"
                      }`}
                    >
                      <svg
                        className={`w-5 h-5 ${invoice.status === "paid" ? "text-emerald-600" : "text-slate-500"}`}
                        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>

                    {/* Invoice Details */}
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-slate-900">
                          {invoice.number || invoice.id.slice(-8).toUpperCase()}
                        </span>
                        {getStatusBadge(invoice.status)}
                      </div>
                      <div className="mt-0.5 text-sm text-slate-500">
                        {getBillingReasonLabel(invoice.billingReason)} •{" "}
                        {formatDate(invoice.createdAt)}
                      </div>
                    </div>
                  </div>

                  {/* Amount and Actions */}
                  <div className="flex items-center gap-4">
                    <div className={`text-right ${isAr ? "text-left" : ""}`}>
                      <div className="font-semibold text-slate-900">
                        {formatCurrency(invoice.total, invoice.currency)}
                      </div>
                      {invoice.amountRemaining > 0 && (
                        <div className="text-xs text-amber-600">
                          {isAr ? "متبقي:" : "Due:"}{" "}
                          {formatCurrency(
                            invoice.amountRemaining,
                            invoice.currency,
                          )}
                        </div>
                      )}
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-2">
                      {invoice.hostedInvoiceUrl && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            window.open(invoice.hostedInvoiceUrl!, "_blank");
                          }}
                          className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-700 transition-colors"
                          title={isAr ? "عرض الفاتورة" : "View Invoice"}
                        >
                          <svg
                            className="w-4 h-4"
                            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>
                        </button>
                      )}
                      {invoice.invoicePdf && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            window.open(invoice.invoicePdf!, "_blank");
                          }}
                          className="p-2 rounded-lg text-emerald-500 hover:bg-emerald-50 hover:text-emerald-700 transition-colors"
                          title={isAr ? "تحميل PDF" : "Download PDF"}
                        >
                          <svg
                            className="w-4 h-4"
                            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>
                        </button>
                      )}
                      <svg
                        className={`w-4 h-4 text-slate-400 transition-transform ${expandedInvoice === invoice.id ? "rotate-180" : ""}`}
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M19 9l-7 7-7-7"
                        />
                      </svg>
                    </div>
                  </div>
                </div>
              </div>

              {/* Expanded Details */}
              {expandedInvoice === invoice.id && (
                <div className="px-4 pb-4">
                  <div className="ml-14 p-4 bg-slate-50 rounded-lg">
                    {/* Period */}
                    {invoice.periodStart && invoice.periodEnd && (
                      <div className="mb-3 text-sm">
                        <span className="text-slate-500">
                          {isAr ? "الفترة:" : "Period:"}
                        </span>
                        <span className="ml-2 text-slate-700">
                          {formatDate(invoice.periodStart)} -{" "}
                          {formatDate(invoice.periodEnd)}
                        </span>
                      </div>
                    )}

                    {/* Line Items */}
                    {invoice.lineItems.length > 0 && (
                      <div className="space-y-2">
                        <div className="text-sm font-medium text-slate-700">
                          {isAr ? "تفاصيل الفاتورة" : "Invoice Details"}
                        </div>
                        <div className="space-y-1">
                          {invoice.lineItems.map((item) => (
                            <div
                              key={item.id}
                              className="flex justify-between text-sm"
                            >
                              <span className="text-slate-600">
                                {item.description || "Item"}
                                {item.quantity &&
                                  item.quantity > 1 &&
                                  ` x${item.quantity}`}
                              </span>
                              <span className="text-slate-900">
                                {formatCurrency(item.amount, invoice.currency)}
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Summary */}
                    <div className="mt-3 pt-3 border-t border-slate-200 space-y-1">
                      <div className="flex justify-between text-sm">
                        <span className="text-slate-500">
                          {isAr ? "المجموع الفرعي" : "Subtotal"}
                        </span>
                        <span className="text-slate-700">
                          {formatCurrency(invoice.subtotal, invoice.currency)}
                        </span>
                      </div>
                      {invoice.tax > 0 && (
                        <div className="flex justify-between text-sm">
                          <span className="text-slate-500">
                            {isAr ? "الضريبة" : "Tax"}
                          </span>
                          <span className="text-slate-700">
                            {formatCurrency(invoice.tax, invoice.currency)}
                          </span>
                        </div>
                      )}
                      <div className="flex justify-between text-sm font-semibold">
                        <span className="text-slate-700">
                          {isAr ? "الإجمالي" : "Total"}
                        </span>
                        <span className="text-slate-900">
                          {formatCurrency(invoice.total, invoice.currency)}
                        </span>
                      </div>
                      {invoice.amountPaid > 0 &&
                        invoice.amountPaid !== invoice.total && (
                          <div className="flex justify-between text-sm text-emerald-600">
                            <span>{isAr ? "المدفوع" : "Paid"}</span>
                            <span>
                              {formatCurrency(
                                invoice.amountPaid,
                                invoice.currency,
                              )}
                            </span>
                          </div>
                        )}
                    </div>

                    {/* Paid Date */}
                    {invoice.paidAt && (
                      <div className="mt-3 text-xs text-emerald-600">
                        {isAr ? "تم الدفع في" : "Paid on"}{" "}
                        {formatDate(invoice.paidAt)}
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Load More */}
      {hasMore && (
        <div className="p-4 border-t border-slate-100 text-center">
          <button
            onClick={loadMore}
            disabled={loadingMore}
            className="px-4 py-2 text-sm font-medium text-brand-green hover:text-brand-greenHover disabled:opacity-50"
          >
            {loadingMore ? (
              <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 ? (
              "تحميل المزيد"
            ) : (
              "Load More"
            )}
          </button>
        </div>
      )}
    </div>
  );
}
