import { useState } from 'react';
import { Receipt, Download, Loader2, ChevronLeft, ChevronRight, Clock } from 'lucide-react';
import type { InvoiceResponse } from '@/infrastructure/http/api/subscription';
import { subscriptionApi } from '@/infrastructure/http/api/subscription';
import type { PaginationMeta } from '@archer/api-interface/schemas/shared/pagination-meta.response';
import { useTranslation } from '@/i18n/TranslationProvider';

interface InvoiceListProps {
  invoices: InvoiceResponse[];
  meta?: PaginationMeta;
  isLoading?: boolean;
  onPageChange?: (page: number) => void;
  onPayNow?: (transactionId: string) => void;
}

const statusColors: Record<string, string> = {
  completed: 'bg-green-100 text-green-700',
  pending: 'bg-yellow-100 text-yellow-700',
  failed: 'bg-red-100 text-red-700',
  refunded: 'bg-gray-100 text-gray-700',
};

export function InvoiceList({ invoices, meta, isLoading, onPageChange, onPayNow }: InvoiceListProps) {
  const { t, locale } = useTranslation();
  const [downloadingId, setDownloadingId] = useState<string | null>(null);

  const handleDownloadPdf = async (invoice: InvoiceResponse) => {
    setDownloadingId(invoice.id);
    try {
      const blob = await subscriptionApi.downloadInvoicePdf(invoice.id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = invoice.invoiceNumber
        ? `RE-${invoice.invoiceNumber}.pdf`
        : `invoice-${invoice.id}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      // silently fail — button only shown when hasPdf is true
    } finally {
      setDownloadingId(null);
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-16 bg-muted animate-pulse rounded-lg" />
        ))}
      </div>
    );
  }

  if (invoices.length === 0) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        <Receipt className="h-8 w-8 mx-auto mb-2 opacity-50" />
        <p className="text-sm">{t('subscription.noPaymentHistory')}</p>
      </div>
    );
  }

  return (
    <div>
      <div className="space-y-2">
        {invoices.map((invoice) => (
          <div
            key={invoice.id}
            className="flex items-center justify-between p-4 bg-card rounded-lg border border-border"
          >
            <div className="flex items-center gap-3 min-w-0">
              <Receipt className="h-4 w-4 text-muted-foreground shrink-0" />
              <div className="min-w-0">
                <p className="text-sm font-medium text-foreground truncate">
                  {invoice.description || t('subscription.payment')}
                </p>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span>{new Date(invoice.createdAt).toLocaleDateString(locale)}</span>
                  {invoice.invoiceNumber && (
                    <>
                      <span>·</span>
                      <span className="font-mono">{invoice.invoiceNumber}</span>
                    </>
                  )}
                </div>
              </div>
            </div>
            <div className="flex items-center gap-3 shrink-0">
              <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${statusColors[invoice.status] || 'bg-gray-100 text-gray-700'}`}>
                {invoice.status}
              </span>
              <div className="text-right w-28">
                {invoice.originalAmount && invoice.discountAmount ? (
                  <>
                    <span className="text-xs text-muted-foreground line-through block">
                      {'\u20AC'}{invoice.originalAmount.toFixed(2)}
                    </span>
                    <span className="text-sm font-semibold text-foreground">
                      {'\u20AC'}{invoice.amount.toFixed(2)}
                    </span>
                    {invoice.appliedCampaigns && invoice.appliedCampaigns.length > 0 && (
                      <span className="text-[10px] text-green-600 block">
                        {invoice.appliedCampaigns.map(c => c.name[locale] || c.name.en || '').filter(Boolean).join(', ')}
                      </span>
                    )}
                  </>
                ) : (
                  <span className="text-sm font-semibold text-foreground">
                    {'\u20AC'}{invoice.amount.toFixed(2)}
                  </span>
                )}
              </div>
              {invoice.status === 'pending' && onPayNow ? (
                <button
                  data-testid="invoice-pay-now"
                  onClick={() => onPayNow(invoice.id)}
                  className="text-xs font-medium bg-orange-600 text-white px-3 py-1.5 rounded-md hover:bg-orange-700 transition-colors"
                >
                  {t('subscription.payNow')}
                </button>
              ) : invoice.hasPdf ? (
                <button
                  onClick={() => handleDownloadPdf(invoice)}
                  disabled={downloadingId === invoice.id}
                  className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-50"
                  title={t('subscription.downloadInvoice')}
                >
                  {downloadingId === invoice.id ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Download className="h-4 w-4" />
                  )}
                </button>
              ) : invoice.status === 'completed' ? (
                <div className="p-1.5 relative group">
                  <Clock className="h-4 w-4 text-muted-foreground/50" />
                  <div className="absolute bottom-full right-0 mb-1.5 px-2.5 py-1 bg-foreground text-background text-xs rounded-md whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                    {t('subscription.invoiceReady')}
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        ))}
      </div>

      {meta && meta.totalPages > 1 && (
        <div className="flex items-center justify-between mt-4 pt-4 border-t border-border">
          <span className="text-xs text-muted-foreground">
            {meta.total} {t('common.total')}
          </span>
          <div className="flex items-center gap-2">
            <button
              onClick={() => onPageChange?.(meta.page - 1)}
              disabled={meta.page <= 1}
              className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30"
            >
              <ChevronLeft className="h-4 w-4" />
            </button>
            <span className="text-xs text-muted-foreground">
              {meta.page} / {meta.totalPages}
            </span>
            <button
              onClick={() => onPageChange?.(meta.page + 1)}
              disabled={meta.page >= meta.totalPages}
              className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30"
            >
              <ChevronRight className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
