'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { usePortalAuthStore } from '@/lib/portal-auth-store';
import portalApi from '@/lib/portal-api';
import { formatCurrency, formatDate } from '@/lib/utils';

interface PortalInvoice {
  id: string;
  invoiceNumber?: string;
  total: number;
  balance: number;
  dueDate?: string;
  status: string;
}

const statusBadge: Record<string, { bg: string; text: string }> = {
  PAID:    { bg: '#DCFCE7', text: '#16A34A' },
  PARTIAL: { bg: '#FEF9C3', text: '#CA8A04' },
  OVERDUE: { bg: '#FEE2E2', text: '#DC2626' },
  SENT:    { bg: '#F1F5F9', text: '#64748B' },
  DRAFT:   { bg: '#F1F5F9', text: '#64748B' },
  VOID:    { bg: '#F1F5F9', text: '#94A3B8' },
};

export default function PortalInvoicesPage() {
  const router = useRouter();
  const { isAuthenticated } = usePortalAuthStore();
  const [mounted, setMounted] = useState(false);
  const [invoices, setInvoices] = useState<PortalInvoice[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => { setMounted(true); }, []);

  useEffect(() => {
    if (!mounted) return;
    if (!isAuthenticated) { router.replace('/portal/login'); return; }
    portalApi.get('/api/v1/portal/invoices')
      .then((res) => {
        const data = res.data;
        setInvoices(Array.isArray(data) ? data : data.data ?? []);
      })
      .catch(() => setError('Failed to load invoices.'))
      .finally(() => setLoading(false));
  }, [mounted, isAuthenticated, router]);

  if (!mounted || !isAuthenticated) return null;

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '32px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <Link href="/portal/dashboard" style={{ fontSize: 13, color: '#0891B2', textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 4 }}>
          ← Back
        </Link>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', margin: 0 }}>Invoice History</h1>
      </div>

      {error && (
        <div style={{ backgroundColor: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 8, padding: '12px 16px', color: '#DC2626', fontSize: 14, marginBottom: 20 }}>
          {error}
        </div>
      )}

      <div style={{ backgroundColor: '#ffffff', borderRadius: 12, border: '1px solid #E2E8F0', overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Loading…</div>
        ) : invoices.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>No invoices found.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#F8FAFC', borderBottom: '1px solid #E2E8F0' }}>
                {['Invoice #', 'Amount', 'Balance', 'Due Date', 'Status'].map((h) => (
                  <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {invoices.map((inv, i) => {
                const badge = statusBadge[inv.status] ?? statusBadge.SENT;
                return (
                  <tr key={inv.id} style={{ borderBottom: i < invoices.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
                    <td style={{ padding: '12px 16px', fontSize: 13, color: '#0F172A', fontFamily: 'Fira Code, monospace' }}>
                      {inv.invoiceNumber ?? inv.id.slice(0, 8)}
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 14, color: '#0F172A' }}>
                      {formatCurrency(Number(inv.total ?? 0))}
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 14, fontWeight: Number(inv.balance) > 0 ? 600 : 400, color: Number(inv.balance) > 0 ? '#DC2626' : '#64748B' }}>
                      {formatCurrency(Number(inv.balance ?? 0))}
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 14, color: '#64748B' }}>
                      {inv.dueDate ? formatDate(inv.dueDate) : '—'}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{ fontSize: 12, fontWeight: 600, padding: '3px 10px', borderRadius: 20, backgroundColor: badge.bg, color: badge.text }}>
                        {inv.status}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
