'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ExternalLink, Receipt, Loader2, Download } from 'lucide-react';
import { useLanguage } from '@/lib/i18n';
import { cn } from '@/lib/utils';

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

export function BillingHistory() {
  const { t } = useLanguage();
  const [portalLoading, setPortalLoading] = useState(false);

  const { data: invoices, isLoading, error } = useQuery<Invoice[]>({
    queryKey: ['billing', 'invoices'],
    queryFn: async () => {
      const res = await fetch('/api/billing/invoices');
      if (!res.ok) throw new Error('Failed to fetch invoices');
      return res.json();
    },
  });

  const handleOpenPortal = async () => {
    setPortalLoading(true);
    try {
      const res = await fetch('/api/billing/portal', { method: 'POST' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? 'Failed');
      window.location.href = data.url;
    } catch {
      // ignore
    } finally {
      setPortalLoading(false);
    }
  };

  const formatAmount = (amount: number, currency: string) => {
    try {
      const locale = typeof window !== 'undefined' ? window.navigator.language : 'fr-FR';
      return new Intl.NumberFormat(locale, {
        style: 'currency',
        currency: currency.toUpperCase(),
      }).format(amount / 100);
    } catch {
      return `${(amount / 100).toFixed(2)} ${currency.toUpperCase()}`;
    }
  };

  const formatDate = (timestamp: number) => {
    try {
      const date = new Date(timestamp * 1000);
      const locale = typeof window !== 'undefined' ? window.navigator.language : 'fr-FR';
      return new Intl.DateTimeFormat(locale, {
        day: 'numeric',
        month: 'short',
        year: 'numeric',
      }).format(date);
    } catch {
      return '—';
    }
  };

  const getStatusBadge = (status: string | null) => {
    const s = status?.toLowerCase();
    if (s === 'paid') {
      return 'bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800/50';
    }
    if (s === 'open' || s === 'pending') {
      return 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/20';
    }
    return 'bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20';
  };

  return (
    <div className="bg-white/40 dark:bg-white/5 border border-border rounded-3xl p-8 space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-paper dark:bg-white/10 text-concrete rounded-2xl">
            <Receipt size={20} />
          </div>
          <div>
            <h4 className="text-sm font-bold text-ink">{t('billing.billingHistory') || 'Historique de facturation'}</h4>
            <p className="text-[10px] text-concrete uppercase tracking-widest">{t('billing.invoices') || 'Factures & reçus'}</p>
          </div>
        </div>

        <button
          type="button"
          onClick={handleOpenPortal}
          disabled={portalLoading}
          className="flex items-center gap-2 text-[10px] font-bold text-brand-accent uppercase tracking-widest hover:underline disabled:opacity-60"
        >
          {portalLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : <ExternalLink className="h-3 w-3" />}
          {t('billing.viewInvoices') || 'Gérer les factures'}
        </button>
      </div>

      {isLoading && (
        <div className="flex items-center justify-center py-8">
          <Loader2 className="h-5 w-5 animate-spin text-brand-accent" />
        </div>
      )}

      {error && (
        <p className="text-xs text-rose-500 text-center py-4">
          Impossible de charger l'historique de facturation.
        </p>
      )}

      {invoices && invoices.length === 0 && (
        <p className="text-xs text-concrete text-center py-4 italic">
          {t('billing.noInvoices') || 'Aucune facture disponible.'}
        </p>
      )}

      {invoices && invoices.length > 0 && (
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="border-b border-border/40">
                <th className="pb-3 text-[10px] font-bold uppercase tracking-wider text-concrete">{t('billing.invoiceDate') || 'Date'}</th>
                <th className="pb-3 text-[10px] font-bold uppercase tracking-wider text-concrete">{t('billing.invoiceNumber') || 'Numéro'}</th>
                <th className="pb-3 text-[10px] font-bold uppercase tracking-wider text-concrete">{t('billing.invoiceAmount') || 'Montant'}</th>
                <th className="pb-3 text-[10px] font-bold uppercase tracking-wider text-concrete">{t('billing.invoiceStatus') || 'Statut'}</th>
                <th className="pb-3 text-right text-[10px] font-bold uppercase tracking-wider text-concrete">PDF</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/20">
              {invoices.map((invoice) => (
                <tr key={invoice.id} className="group hover:bg-slate-50/50 dark:hover:bg-white/5 transition-colors">
                  <td className="py-4 text-xs font-medium text-ink">{formatDate(invoice.date)}</td>
                  <td className="py-4 text-xs font-mono text-concrete">{invoice.number || '—'}</td>
                  <td className="py-4 text-xs font-semibold text-ink">{formatAmount(invoice.amount, invoice.currency)}</td>
                  <td className="py-4 text-xs">
                    <span className={cn('px-2.5 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider', getStatusBadge(invoice.status))}>
                      {invoice.status ? t(`billing.${invoice.status.toLowerCase()}`) || invoice.status : '—'}
                    </span>
                  </td>
                  <td className="py-4 text-right">
                    {invoice.pdfUrl ? (
                      <a
                        href={invoice.pdfUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center justify-center p-2 rounded-lg text-concrete hover:text-brand-accent hover:bg-brand-accent/10 transition-all"
                        title="Download PDF"
                      >
                        <Download size={14} />
                      </a>
                    ) : (
                      <span className="text-xs text-concrete">—</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
