/**
 * Invoices Card Component
 * Displays Stripe invoices with payment history using /api/billing/invoices
 * Shows PDF downloads, payment summary, and next billing date
 */

"use client";

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

interface Invoice {
  id: string;
  number: string | null;
  date: string;
  dueDate: string | null;
  amount: number;
  amountDue: number;
  currency: string;
  status: "paid" | "open" | "void" | "uncollectible";
  pdfUrl: string | null;
  hostedUrl: string | null;
  description: string;
  periodStart: string | null;
  periodEnd: string | null;
}

interface PaymentSummary {
  totalPaid: number;
  invoiceCount: number;
  lastPayment: {
    amount: number;
    date: string;
    invoiceNumber: string;
  } | null;
  nextBilling: {
    amount: number;
    date: string;
    status: string;
  } | null;
}

interface InvoicesData {
  hasInvoices: boolean;
  invoices: Invoice[];
  summary: PaymentSummary;
  meta: {
    count: number;
    hasMore: boolean;
    limit: number;
  };
}

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

export default function InvoicesCard({ lang, limit = 10 }: InvoicesCardProps) {
  const [data, setData] = useState<InvoicesData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAll, setShowAll] = useState(false);

  const isAr = lang === "ar";

  useEffect(() => {
    async function fetchInvoices() {
      try {
        const response = await fetch(`/api/billing/invoices?limit=${limit}`);

        if (!response.ok) {
          if (response.status === 404) {
            setError(isAr ? "لا توجد فواتير" : "No invoices found");
          } else {
            const errorData = await response.json();
            throw new Error(errorData.error || "Failed to fetch invoices");
          }
          return;
        }

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

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

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <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 || !data?.hasInvoices) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="text-center py-8">
          <div className="text-4xl mb-4">📄</div>
          <p className="text-sm text-slate-600">
            {error || (isAr ? "لا توجد فواتير بعد" : "No invoices yet")}
          </p>
          <p className="text-xs text-slate-400 mt-2">
            {isAr
              ? "ستظهر الفواتير هنا بعد أول دفعة"
              : "Invoices will appear here after your first payment"}
          </p>
        </div>
      </div>
    );
  }

  const displayInvoices = showAll ? data.invoices : data.invoices.slice(0, 5);

  return (
    <div className="space-y-4">
      {/* Summary Card */}
      <div className="rounded-xl bg-gradient-to-br from-slate-900 to-slate-800 p-6 text-white shadow-lg">
        <h3 className="text-sm font-medium text-slate-300 uppercase tracking-wide mb-4">
          {isAr ? "ملخص الدفع" : "Payment Summary"}
        </h3>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <p className="text-xs text-slate-400">
              {isAr ? "إجمالي المدفوعات" : "Total Paid"}
            </p>
            <p className="text-2xl font-bold mt-1">
              ${data.summary.totalPaid.toFixed(2)}
            </p>
          </div>

          {data.summary.lastPayment && (
            <div>
              <p className="text-xs text-slate-400">
                {isAr ? "آخر دفعة" : "Last Payment"}
              </p>
              <p className="text-lg font-bold mt-1">
                ${data.summary.lastPayment.amount.toFixed(2)}
              </p>
              <p className="text-xs text-slate-400">
                {new Date(data.summary.lastPayment.date).toLocaleDateString(
                  isAr ? "ar-SA" : "en-US",
                  { month: "short", day: "numeric" },
                )}
              </p>
            </div>
          )}
        </div>

        {data.summary.nextBilling && (
          <div className="mt-4 pt-4 border-t border-slate-700">
            <div className="flex items-center justify-between">
              <span className="text-xs text-slate-400">
                {isAr ? "الفاتورة القادمة" : "Next Billing"}
              </span>
              <div className="text-right">
                <p className="text-base font-bold">
                  ${data.summary.nextBilling.amount.toFixed(2)}
                </p>
                <p className="text-xs text-slate-400">
                  {new Date(data.summary.nextBilling.date).toLocaleDateString(
                    isAr ? "ar-SA" : "en-US",
                    { month: "short", day: "numeric", year: "numeric" },
                  )}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Invoices List */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "📄 الفواتير" : "📄 Invoices"}
          </h3>
          <span className="text-xs text-slate-500">
            {isAr
              ? `${data.invoices.length} فاتورة`
              : `${data.invoices.length} invoices`}
          </span>
        </div>

        <div className="space-y-3">
          {displayInvoices.map((invoice) => (
            <InvoiceItem key={invoice.id} invoice={invoice} lang={lang} />
          ))}
        </div>

        {/* Show More Button */}
        {data.invoices.length > 5 && (
          <div className="mt-4 text-center">
            <button
              onClick={() => setShowAll(!showAll)}
              className="text-sm text-brand-green hover:underline font-medium"
            >
              {showAll
                ? isAr
                  ? "عرض أقل"
                  : "Show Less"
                : isAr
                  ? `عرض جميع الفواتير (${data.invoices.length})`
                  : `Show All Invoices (${data.invoices.length})`}
            </button>
          </div>
        )}

        {data.meta.hasMore && (
          <p className="mt-3 text-xs text-center text-slate-400">
            {isAr
              ? "يوجد المزيد من الفواتير. اتصل بالدعم للحصول على السجل الكامل."
              : "More invoices available. Contact support for complete history."}
          </p>
        )}
      </div>
    </div>
  );
}

// Individual Invoice Item Component
function InvoiceItem({ invoice, lang }: { invoice: Invoice; lang: Lang }) {
  const isAr = lang === "ar";

  // Status configuration
  const statusConfig: Record<
    string,
    { bg: string; text: string; label: { en: string; ar: string } }
  > = {
    paid: {
      bg: "bg-emerald-50",
      text: "text-emerald-700",
      label: { en: "Paid", ar: "مدفوع" },
    },
    open: {
      bg: "bg-blue-50",
      text: "text-blue-700",
      label: { en: "Open", ar: "مفتوح" },
    },
    void: {
      bg: "bg-slate-50",
      text: "text-slate-700",
      label: { en: "Void", ar: "ملغى" },
    },
    uncollectible: {
      bg: "bg-red-50",
      text: "text-red-700",
      label: { en: "Uncollectible", ar: "غير قابل للتحصيل" },
    },
  };

  const status = statusConfig[invoice.status] || statusConfig.paid;

  return (
    <div className="rounded-lg border border-slate-200 p-4 hover:border-brand-green transition-colors">
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <p className="font-semibold text-slate-900">
              {invoice.number || `#${invoice.id.slice(-8)}`}
            </p>
            <span
              className={`px-2 py-0.5 rounded-full text-xs font-medium ${status.bg} ${status.text}`}
            >
              {isAr ? status.label.ar : status.label.en}
            </span>
          </div>

          <p className="text-xs text-slate-500">
            {new Date(invoice.date).toLocaleDateString(
              isAr ? "ar-SA" : "en-US",
              {
                year: "numeric",
                month: "long",
                day: "numeric",
              },
            )}
          </p>

          {invoice.description && (
            <p className="text-xs text-slate-600 mt-2">{invoice.description}</p>
          )}

          {invoice.periodStart && invoice.periodEnd && (
            <p className="text-xs text-slate-400 mt-1">
              {isAr ? "الفترة: " : "Period: "}
              {new Date(invoice.periodStart).toLocaleDateString(
                isAr ? "ar-SA" : "en-US",
                {
                  month: "short",
                  day: "numeric",
                },
              )}
              {" - "}
              {new Date(invoice.periodEnd).toLocaleDateString(
                isAr ? "ar-SA" : "en-US",
                {
                  month: "short",
                  day: "numeric",
                },
              )}
            </p>
          )}
        </div>

        <div className="text-right">
          <p className="text-lg font-bold text-slate-900">
            ${invoice.amount.toFixed(2)}
          </p>
          <p className="text-xs text-slate-500">{invoice.currency}</p>
        </div>
      </div>

      {/* Actions */}
      <div className="flex flex-wrap gap-2 mt-3 pt-3 border-t border-slate-100">
        {invoice.pdfUrl && (
          <a
            href={invoice.pdfUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 rounded-lg bg-slate-100 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-200 transition-colors"
          >
            <span>📄</span>
            <span>{isAr ? "تنزيل PDF" : "Download PDF"}</span>
          </a>
        )}

        {invoice.hostedUrl && (
          <a
            href={invoice.hostedUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 rounded-lg bg-slate-100 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-200 transition-colors"
          >
            <span>🔗</span>
            <span>{isAr ? "عرض الفاتورة" : "View Invoice"}</span>
          </a>
        )}

        {invoice.status === "open" && (
          <button
            onClick={() => window.open(invoice.hostedUrl || "#", "_blank")}
            className="inline-flex items-center gap-1.5 rounded-lg bg-brand-green px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-greenHover transition-colors"
          >
            <span>💳</span>
            <span>{isAr ? "ادفع الآن" : "Pay Now"}</span>
          </button>
        )}
      </div>
    </div>
  );
}
