import { useState, useMemo, CSSProperties } from 'react';
import PageHeader from '../components/PageHeader';

interface Invoice {
    id: number;
    number: string;
    client_name: string;
    amount: number;
    due_date: string;
    status: 'pending' | 'overdue' | 'paid';
    days_overdue: number;
    issued_date: string;
    payment_method?: string;
}

/**
 * 💳 PÁGINA: FACTURACIÓN ONLINE
 * 
 * ✅ ESTILO ACTUALIZADO - Usa el diseño premium estándar
 */

// Mock data
const mockInvoices: Invoice[] = [
    { id: 1, number: 'INV-2026-00045', client_name: 'Gamma Retail SA', amount: 320.00, due_date: '2025-12-31', status: 'overdue', days_overdue: 25, issued_date: '2025-12-15' },
    { id: 2, number: 'INV-2026-00051', client_name: 'Delta Industries', amount: 1250.00, due_date: '2026-01-15', status: 'overdue', days_overdue: 10, issued_date: '2025-12-30' },
    { id: 3, number: 'INV-2026-00058', client_name: 'Acme Corporation', amount: 450.00, due_date: '2026-02-01', status: 'pending', days_overdue: 0, issued_date: '2026-01-15' },
    { id: 4, number: 'INV-2026-00060', client_name: 'Beta Technologies', amount: 890.00, due_date: '2026-02-10', status: 'pending', days_overdue: 0, issued_date: '2026-01-20' },
    { id: 5, number: 'INV-2026-00042', client_name: 'Epsilon Tech', amount: 3200.00, due_date: '2026-01-22', status: 'paid', days_overdue: 0, issued_date: '2026-01-05', payment_method: 'Transferencia' },
    { id: 6, number: 'INV-2026-00038', client_name: 'Zeta Media', amount: 780.00, due_date: '2026-01-10', status: 'paid', days_overdue: 0, issued_date: '2025-12-25', payment_method: 'Tarjeta' },
    { id: 7, number: 'INV-2026-00035', client_name: 'Sigma Corp', amount: 1560.00, due_date: '2026-01-05', status: 'paid', days_overdue: 0, issued_date: '2025-12-20', payment_method: 'Efectivo' },
];

const statusConfig: Record<string, { label: string; class: string }> = {
    pending: { label: 'Pendiente', class: 'badge-warning' },
    overdue: { label: 'Vencida', class: 'badge-danger' },
    paid: { label: 'Pagada', class: 'badge-success' },
};

export default function Billing() {
    const [invoices, setInvoices] = useState<Invoice[]>(mockInvoices);
    const [search, setSearch] = useState('');
    const [filterStatus, setFilterStatus] = useState<string>('all');
    const [showNewInvoiceModal, setShowNewInvoiceModal] = useState(false);

    const filteredInvoices = useMemo(() => {
        return invoices.filter(invoice => {
            const matchSearch = invoice.number.toLowerCase().includes(search.toLowerCase()) ||
                invoice.client_name.toLowerCase().includes(search.toLowerCase());
            const matchStatus = filterStatus === 'all' || invoice.status === filterStatus;
            return matchSearch && matchStatus;
        });
    }, [invoices, search, filterStatus]);

    // Stats
    const stats = useMemo(() => ({
        total: invoices.length,
        pending: invoices.filter(i => i.status === 'pending').length,
        overdue: invoices.filter(i => i.status === 'overdue').length,
        paid: invoices.filter(i => i.status === 'paid').length,
        totalAmount: invoices.reduce((sum, i) => sum + i.amount, 0),
        pendingAmount: invoices.filter(i => i.status === 'pending').reduce((sum, i) => sum + i.amount, 0),
        overdueAmount: invoices.filter(i => i.status === 'overdue').reduce((sum, i) => sum + i.amount, 0),
        paidAmount: invoices.filter(i => i.status === 'paid').reduce((sum, i) => sum + i.amount, 0),
    }), [invoices]);

    const metricCards = [
        {
            icon: '💰',
            label: 'Ingresos Totales',
            value: `$${stats.totalAmount.toLocaleString('es-ES', { minimumFractionDigits: 2 })}`,
            subtext: `${stats.total} facturas`,
            gradient: 'linear-gradient(135deg, #10b981, #059669)',
            glow: 'rgba(16, 185, 129, 0.4)',
        },
        {
            icon: '⏳',
            label: 'Pendientes',
            value: `$${stats.pendingAmount.toLocaleString('es-ES', { minimumFractionDigits: 2 })}`,
            subtext: `${stats.pending} facturas`,
            gradient: 'linear-gradient(135deg, #f59e0b, #d97706)',
            glow: 'rgba(245, 158, 11, 0.4)',
        },
        {
            icon: '⚠️',
            label: 'Vencidas',
            value: `$${stats.overdueAmount.toLocaleString('es-ES', { minimumFractionDigits: 2 })}`,
            subtext: `${stats.overdue} facturas`,
            gradient: 'linear-gradient(135deg, #ef4444, #dc2626)',
            glow: 'rgba(239, 68, 68, 0.4)',
            alert: stats.overdue > 0,
        },
        {
            icon: '✅',
            label: 'Pagadas',
            value: `$${stats.paidAmount.toLocaleString('es-ES', { minimumFractionDigits: 2 })}`,
            subtext: `${stats.paid} facturas`,
            gradient: 'linear-gradient(135deg, #3b82f6, #2563eb)',
            glow: 'rgba(59, 130, 246, 0.4)',
        },
    ];

    return (
        <div className="animate-fadeIn">
            {/* Page Header */}
            <PageHeader
                title="Facturación Online"
                subtitle="Gestiona las facturas y pagos de tus clientes"
                actions={
                    <>
                        <button className="btn btn-secondary">
                            📊 Reportes
                        </button>
                        <button className="btn btn-primary" onClick={() => setShowNewInvoiceModal(true)}>
                            ➕ Nueva Factura
                        </button>
                    </>
                }
                stats={[
                    { icon: '📅', label: 'Hoy', value: new Date().toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'short' }) },
                    { icon: '⚠️', label: 'Vencidas', value: stats.overdue, color: 'var(--color-danger)' },
                ]}
            />

            {/* Metric Cards Grid */}
            <div className="cards-grid">
                {metricCards.map((card, index) => (
                    <div
                        key={index}
                        className="card metric-card"
                        style={{ '--card-glow': card.glow } as CSSProperties}
                    >
                        <div
                            className="metric-icon"
                            style={{ background: card.gradient }}
                        >
                            {card.icon}
                        </div>
                        <div className="metric-content">
                            <div className="metric-label">{card.label}</div>
                            <div className="metric-value">{card.value}</div>
                            {card.subtext && (
                                <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
                                    {card.subtext}
                                </div>
                            )}
                            {card.alert && (
                                <div className="metric-change negative" style={{ background: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-danger)' }}>
                                    ⚠️ Requiere atención
                                </div>
                            )}
                        </div>
                    </div>
                ))}
            </div>

            {/* Filters */}
            <div className="filters" style={{ marginTop: '2rem' }}>
                <div className="form-group" style={{ marginBottom: 0, flex: 1, maxWidth: '350px' }}>
                    <input
                        type="text"
                        className="form-input"
                        placeholder="🔍 Buscar por número o cliente..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                    />
                </div>

                <select
                    className="form-select"
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value)}
                    style={{ minWidth: '150px' }}
                >
                    <option value="all">Todos los estados</option>
                    <option value="pending">⏳ Pendientes</option>
                    <option value="overdue">⚠️ Vencidas</option>
                    <option value="paid">✅ Pagadas</option>
                </select>

                {(search || filterStatus !== 'all') && (
                    <button
                        className="btn btn-ghost btn-sm"
                        onClick={() => { setSearch(''); setFilterStatus('all'); }}
                    >
                        ✕ Limpiar filtros
                    </button>
                )}
            </div>

            {/* Invoices Table */}
            <div style={{ marginTop: '1.5rem' }}>
                <div className="table-container">
                    <div className="table-header">
                        <h2 className="table-title">💳 Facturas</h2>
                        <button className="btn btn-ghost btn-sm">
                            🔄 Actualizar
                        </button>
                    </div>
                    <div className="table-wrapper">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Factura</th>
                                    <th>Cliente</th>
                                    <th>Monto</th>
                                    <th>Fecha Emisión</th>
                                    <th>Vencimiento</th>
                                    <th>Estado</th>
                                    <th>Método Pago</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredInvoices.length === 0 ? (
                                    <tr>
                                        <td colSpan={8} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
                                            <div style={{ fontSize: '2rem', marginBottom: '1rem' }}>💳</div>
                                            <div>No hay facturas que coincidan con los filtros</div>
                                        </td>
                                    </tr>
                                ) : (
                                    filteredInvoices.map((invoice) => (
                                        <tr key={invoice.id}>
                                            <td>
                                                <div className="cell-main">{invoice.number}</div>
                                            </td>
                                            <td style={{ fontSize: '0.85rem' }}>{invoice.client_name}</td>
                                            <td style={{ fontWeight: 600, color: 'var(--color-success)' }}>
                                                ${invoice.amount.toLocaleString('es-ES', { minimumFractionDigits: 2 })}
                                            </td>
                                            <td>
                                                {new Date(invoice.issued_date).toLocaleDateString('es-ES', {
                                                    day: '2-digit',
                                                    month: 'short',
                                                    year: '2-digit'
                                                })}
                                            </td>
                                            <td>
                                                <div className="cell-main">
                                                    {new Date(invoice.due_date).toLocaleDateString('es-ES', {
                                                        day: '2-digit',
                                                        month: 'short',
                                                        year: '2-digit'
                                                    })}
                                                </div>
                                                {invoice.status === 'overdue' && (
                                                    <div className="cell-secondary" style={{ color: 'var(--color-danger)' }}>
                                                        {invoice.days_overdue} días vencida
                                                    </div>
                                                )}
                                            </td>
                                            <td>
                                                <span className={`badge ${statusConfig[invoice.status].class}`}>
                                                    <span className="badge-dot"></span>
                                                    {statusConfig[invoice.status].label}
                                                </span>
                                            </td>
                                            <td style={{ fontSize: '0.85rem' }}>
                                                {invoice.payment_method || <span style={{ color: 'var(--text-muted)' }}>—</span>}
                                            </td>
                                            <td>
                                                <div style={{ display: 'flex', gap: '0.5rem' }}>
                                                    <button className="btn-icon" title="Ver factura">
                                                        👁️
                                                    </button>
                                                    <button className="btn-icon" title="Descargar PDF">
                                                        📄
                                                    </button>
                                                    {invoice.status !== 'paid' && (
                                                        <button className="btn-icon" title="Marcar como pagada" style={{ color: 'var(--color-success)' }}>
                                                            ✅
                                                        </button>
                                                    )}
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            {/* Results Count */}
            <div style={{
                marginTop: '1rem',
                fontSize: '0.85rem',
                color: 'var(--text-muted)',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
            }}>
                <span>Mostrando {filteredInvoices.length} de {invoices.length} facturas</span>
                <button className="btn btn-ghost btn-sm">📥 Exportar</button>
            </div>

            {/* New Invoice Modal */}
            {showNewInvoiceModal && (
                <div style={{
                    position: 'fixed',
                    inset: 0,
                    background: 'rgba(0, 0, 0, 0.7)',
                    backdropFilter: 'blur(4px)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 9999,
                    padding: '1rem'
                }} onClick={() => setShowNewInvoiceModal(false)}>
                    <div className="card" style={{
                        maxWidth: '600px',
                        width: '100%',
                        maxHeight: '90vh',
                        overflowY: 'auto'
                    }} onClick={(e) => e.stopPropagation()}>
                        <div style={{ padding: '1.5rem', borderBottom: '1px solid var(--border-color)' }}>
                            <h2 style={{ fontSize: '1.5rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                💳 Nueva Factura
                            </h2>
                            <p style={{ fontSize: '0.9rem', color: 'var(--text-muted)', marginTop: '0.5rem' }}>
                                Crea una nueva factura para un cliente
                            </p>
                        </div>
                        <form style={{ padding: '1.5rem' }}>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Cliente
                                    </label>
                                    <select className="input" required>
                                        <option value="">Seleccionar cliente</option>
                                        <option>Acme Corporation</option>
                                        <option>Beta Technologies</option>
                                        <option>Gamma Retail SA</option>
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Monto
                                    </label>
                                    <input
                                        type="number"
                                        className="input"
                                        required
                                        placeholder="0.00"
                                        step="0.01"
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Fecha de vencimiento
                                    </label>
                                    <input
                                        type="date"
                                        className="input"
                                        required
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Descripción
                                    </label>
                                    <textarea
                                        className="input"
                                        rows={3}
                                        placeholder="Servicios facturados..."
                                    />
                                </div>
                                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                                    <button type="button" className="btn btn-secondary" onClick={() => setShowNewInvoiceModal(false)}>
                                        Cancelar
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        💳 Crear Factura
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
