'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import Link from 'next/link';
import { apiClient } from '@/infrastructure/api/api-client';
import { FileText, Download } from 'lucide-react';

interface Invoice {
  id: string;
  invoiceNumber: string;
  status: string;
  currency: string;
  totalAmount: number;
  amountDue: number;
  periodStart: string;
  periodEnd: string;
  dueDate: string;
  paidAt: string | null;
  createdAt: string;
}

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    paid: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    open: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    past_due: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    void: 'bg-gray-100 text-gray-600',
  };
  return (
    <span className={`px-2 py-0.5 rounded text-xs font-medium ${colors[status] ?? 'bg-muted text-muted-foreground'}`}>
      {status}
    </span>
  );
}

const PAGE_SIZE = 20;

export default function InvoicesPage() {
  const [page, setPage] = useState(0);
  const { t } = useTranslation('billing');

  const { data, isLoading } = useQuery<{ data: Invoice[]; total: number }>({
    queryKey: ['billing', 'invoices', page],
    queryFn: () => apiClient(`/api/v1/billing/invoices?limit=${PAGE_SIZE}&offset=${page * PAGE_SIZE}`),
  });

  const invoices = data?.data ?? [];
  const total = data?.total ?? 0;
  const totalPages = Math.ceil(total / PAGE_SIZE);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold flex items-center gap-2">
        <FileText className="h-6 w-6" /> {t('invoices.title')}
      </h1>

      <div className="rounded-lg border bg-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50 text-muted-foreground">
              <tr>
                <th className="text-left p-4 font-medium">{t('invoices.invoiceNumber')}</th>
                <th className="text-left p-4 font-medium">{t('invoices.period')}</th>
                <th className="text-left p-4 font-medium">{t('invoices.amount')}</th>
                <th className="text-left p-4 font-medium">{t('invoices.dueDate')}</th>
                <th className="text-left p-4 font-medium">{t('invoices.status')}</th>
                <th className="p-4" />
              </tr>
            </thead>
            <tbody className="divide-y">
              {isLoading ? (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-muted-foreground">{t('invoices.loading')}</td>
                </tr>
              ) : invoices.length === 0 ? (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-muted-foreground">{t('invoices.noInvoices')}</td>
                </tr>
              ) : (
                invoices.map((inv) => (
                  <tr key={inv.id} className="hover:bg-muted/30 transition-colors">
                    <td className="p-4">
                      <Link href={`/billing/invoices/${inv.id}`} className="text-primary hover:underline font-medium">
                        {inv.invoiceNumber}
                      </Link>
                    </td>
                    <td className="p-4 text-muted-foreground">
                      {new Date(inv.periodStart).toLocaleDateString()} – {new Date(inv.periodEnd).toLocaleDateString()}
                    </td>
                    <td className="p-4 font-medium">
                      {inv.currency} {inv.totalAmount.toFixed(2)}
                    </td>
                    <td className="p-4 text-muted-foreground">
                      {new Date(inv.dueDate).toLocaleDateString()}
                    </td>
                    <td className="p-4">
                      <StatusBadge status={inv.status} />
                    </td>
                    <td className="p-4 text-right">
                      {inv.status === 'open' ? (
                        <Link
                          href={`/billing/invoices/${inv.id}?pay=1`}
                          className="text-xs bg-primary text-primary-foreground px-3 py-1.5 rounded-md hover:bg-primary/90"
                        >
                          {t('invoices.payNow')}
                        </Link>
                      ) : (
                        <button className="p-1.5 rounded hover:bg-muted transition-colors" title="Download">
                          <Download className="h-4 w-4 text-muted-foreground" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {totalPages > 1 && (
          <div className="flex items-center justify-between p-4 border-t">
            <span className="text-sm text-muted-foreground">
              {t('invoices.pagination', { current: page + 1, total: totalPages, count: total })}
            </span>
            <div className="flex gap-2">
              <button
                onClick={() => setPage((p) => p - 1)}
                disabled={page === 0}
                className="px-3 py-1.5 rounded border text-sm disabled:opacity-50"
              >
                {t('invoices.previous')}
              </button>
              <button
                onClick={() => setPage((p) => p + 1)}
                disabled={page >= totalPages - 1}
                className="px-3 py-1.5 rounded border text-sm disabled:opacity-50"
              >
                {t('invoices.next')}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
