'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
    ArrowLeft, Receipt, CheckCircle, Clock, FileText, MapPin, Search,
    Trash2, Plus, Download, FileSignature, Edit3, Save, Loader2, AlertCircle, Eye
} from 'lucide-react';
import Link from 'next/link';

interface Props {
    facturaId: string;
    userRole: string;
}

export default function FacturaDetailClient({ facturaId, userRole }: Props) {
    const router = useRouter();
    const [loading, setLoading] = useState(true);
    const [factura, setFactura] = useState<any>(null);
    const [error, setError] = useState('');

    // Modals
    const [showAddPago, setShowAddPago] = useState(false);
    const [newPago, setNewPago] = useState({ importe: '', fechaPago: new Date().toISOString().split('T')[0], metodoPago: 'TRANSFERENCIA_BANCARIA', notas: '' });
    const [savingPago, setSavingPago] = useState(false);

    const fetchFactura = async () => {
        try {
            const res = await fetch(`/api/facturas/${facturaId}`);
            if (!res.ok) throw new Error('Error al cargar la factura');
            const data = await res.json();
            setFactura(data);
        } catch (e: any) {
            setError(e.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchFactura();
    }, [facturaId]);

    const handleAddPago = async () => {
        setSavingPago(true);
        try {
            const res = await fetch(`/api/facturas/${facturaId}/pagos`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(newPago),
            });
            if (res.ok) {
                setShowAddPago(false);
                setNewPago({ importe: '', fechaPago: new Date().toISOString().split('T')[0], metodoPago: 'TRANSFERENCIA_BANCARIA', notas: '' });
                fetchFactura(); // reload to get new balance
            } else {
                alert('Error al añadir el pago');
            }
        } catch (e) {
            console.error(e);
        } finally {
            setSavingPago(false);
        }
    };

    const handleDeletePago = async (pagoId: string) => {
        if (!confirm('¿Eliminar este pago?')) return;
        try {
            const res = await fetch(`/api/facturas/${facturaId}/pagos?pagoId=${pagoId}`, { method: 'DELETE' });
            if (res.ok) fetchFactura();
        } catch (e) { console.error(e); }
    };

    const ESTADO_COLORS: Record<string, string> = {
        PENDIENTE: 'bg-red-100 text-red-700',
        COBRADA_PARCIAL: 'bg-amber-100 text-amber-700',
        COBRADA_TOTAL: 'bg-green-100 text-green-700',
    };

    const ESTADO_LABELS: Record<string, string> = {
        PENDIENTE: 'Pendiente',
        COBRADA_PARCIAL: 'Cobro Parcial',
        COBRADA_TOTAL: 'Cobrada',
    };

    const formatCurrency = (val: number) => new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(val);

    if (loading) return <div className="p-12 text-center"><Loader2 className="w-8 h-8 animate-spin mx-auto text-[#1a365d]" /></div>;
    if (error || !factura) return <div className="p-12 text-center text-red-500">{error || 'No encontrada'}</div>;

    const saldoPendiente = factura.total - factura.importeCobrado;

    return (
        <div className="space-y-6 pb-20 max-w-5xl mx-auto">
            {/* Botón Volver */}
            <button onClick={() => router.back()} className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-900 transition-colors">
                <ArrowLeft className="w-4 h-4" /> Volver a facturas
            </button>

            {/* Header Factura */}
            <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <div className="flex items-center gap-3">
                        <div className="w-12 h-12 bg-[#1a365d]/10 rounded-xl flex items-center justify-center text-[#1a365d]">
                            <Receipt className="w-6 h-6" />
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold text-gray-900">{factura.numero}</h1>
                            <span className={`text-xs px-2 py-0.5 rounded-md font-medium mt-1 inline-block ${ESTADO_COLORS[factura.estadoCobro]}`}>
                                {ESTADO_LABELS[factura.estadoCobro]}
                            </span>
                        </div>
                    </div>
                </div>

                <div className="flex items-center gap-3 w-full md:w-auto">
                    <button
                        onClick={() => window.open(`/api/facturas/${factura.id}/word`, '_blank')}
                        className="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2 border border-[#3182ce] text-[#3182ce] hover:bg-blue-50 rounded-lg text-sm transition font-medium">
                        <FileText className="w-4 h-4" /> Word
                    </button>
                    <button
                        onClick={() => window.open(`/api/facturas/${factura.id}/pdf`, '_blank')}
                        className="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 hover:bg-gray-50 rounded-lg text-sm transition font-medium">
                        <Eye className="w-4 h-4" /> Ver PDF
                    </button>
                    <button
                        onClick={() => window.open(`/api/facturas/${factura.id}/pdf?download=true`, '_blank')}
                        className="flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2 border border-red-300 text-red-700 hover:bg-red-50 rounded-lg text-sm transition font-medium">
                        <Download className="w-4 h-4" /> PDF
                    </button>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Columna Izquierda (Datos Cliente y Líneas) */}
                <div className="lg:col-span-2 space-y-6">
                    {/* Card Cliente */}
                    <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                        <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <FileSignature className="w-5 h-5 text-gray-400" />
                            Datos de Facturación
                        </h3>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <p className="text-xs text-gray-400 mb-1">Cliente</p>
                                <p className="text-sm font-semibold text-gray-900">
                                    {factura.cliente ? (
                                        <Link href={`/dashboard/clientes/${factura.clienteId}`} className="text-[#1a365d] hover:underline">
                                            {factura.cliente.nombre}
                                        </Link>
                                    ) : factura.clienteNombre}
                                </p>
                            </div>
                            <div>
                                <p className="text-xs text-gray-400 mb-1">CIF / NIF</p>
                                <p className="text-sm text-gray-700">{factura.cif || '—'}</p>
                            </div>
                            <div className="sm:col-span-2">
                                <p className="text-xs text-gray-400 mb-1">Dirección Fiscal</p>
                                <p className="text-sm text-gray-700">{factura.direccion || '—'}</p>
                            </div>
                            <div>
                                <p className="text-xs text-gray-400 mb-1">Fecha Emisión</p>
                                <p className="text-sm text-gray-700">{new Date(factura.fechaEmision).toLocaleDateString('es-ES')}</p>
                            </div>
                            <div>
                                <p className="text-xs text-gray-400 mb-1">Forma de Pago</p>
                                <p className="text-sm text-gray-700 font-medium">{factura.formaPago.replace(/_/g, ' ')}</p>
                            </div>
                        </div>
                    </div>

                    {/* Card Líneas */}
                    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                        <div className="px-6 py-4 border-b border-gray-100 bg-gray-50/50 flex justify-between items-center">
                            <h3 className="text-lg font-bold text-gray-900">Conceptos</h3>
                        </div>
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="bg-gray-50 border-b text-gray-500 font-medium">
                                    <tr>
                                        <th className="py-3 px-6">Descripción</th>
                                        <th className="py-3 px-6 text-right">Cant.</th>
                                        <th className="py-3 px-6 text-right">Precio Unit.</th>
                                        <th className="py-3 px-6 text-right">Total</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {factura.lineas?.map((l: any) => (
                                        <tr key={l.id} className="hover:bg-gray-50/50">
                                            <td className="py-3 px-6 text-gray-900">{l.concepto}</td>
                                            <td className="py-3 px-6 text-right text-gray-600">{l.cantidad}</td>
                                            <td className="py-3 px-6 text-right text-gray-600">{formatCurrency(l.precioUnit)}</td>
                                            <td className="py-3 px-6 text-right font-medium text-gray-900">{formatCurrency(l.totalLinea)}</td>
                                        </tr>
                                    ))}
                                    {(!factura.lineas || factura.lineas.length === 0) && (
                                        <tr><td colSpan={4} className="py-8 text-center text-gray-500">Ningún concepto.</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Totales Resumen */}
                        <div className="bg-gray-50 border-t p-6">
                            <div className="w-full max-w-sm ml-auto space-y-3">
                                <div className="flex justify-between text-sm text-gray-600">
                                    <span>Base Imponible:</span>
                                    <span>{formatCurrency(factura.subtotal)}</span>
                                </div>
                                <div className="flex justify-between text-sm text-gray-600">
                                    <span>IVA ({factura.ivaPorcentaje}%):</span>
                                    <span>{formatCurrency(factura.importeIva)}</span>
                                </div>
                                <div className="pt-3 border-t border-gray-200 flex justify-between items-center">
                                    <span className="text-base font-bold text-gray-900">Total Factura:</span>
                                    <span className="text-xl font-bold text-[#1a365d]">{formatCurrency(factura.total)}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Columna Derecha (Panel de Pagos) */}
                <div className="space-y-6">
                    <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                        <h3 className="text-lg font-bold text-gray-900 mb-6 flex items-center gap-2">
                            <Clock className="w-5 h-5 text-amber-500" /> Control de Cobros
                        </h3>

                        <div className="space-y-4 mb-6">
                            <div className="flex justify-between text-sm">
                                <span className="text-gray-500">Total Facturado</span>
                                <span className="font-semibold text-gray-900">{formatCurrency(factura.total)}</span>
                            </div>
                            <div className="flex justify-between text-sm">
                                <span className="text-green-600 font-medium">Importe Cobrado</span>
                                <span className="font-semibold text-green-600">{formatCurrency(factura.importeCobrado)}</span>
                            </div>
                            <div className="pt-3 border-t flex justify-between text-sm">
                                <span className="text-red-500 font-medium">Saldo Pendiente</span>
                                <span className="font-bold text-red-600 text-lg">{formatCurrency(saldoPendiente)}</span>
                            </div>
                        </div>

                        {saldoPendiente > 0 && userRole !== 'operario' && (
                            <button
                                onClick={() => setShowAddPago(!showAddPago)}
                                className="w-full flex items-center justify-center gap-2 py-2.5 bg-[#1a365d]/10 text-[#1a365d] rounded-xl text-sm font-semibold hover:bg-[#1a365d]/20 transition"
                            >
                                <Plus className="w-4 h-4" /> {showAddPago ? 'Añadiendo...' : 'Añadir Cobro'}
                            </button>
                        )}

                        {showAddPago && (
                            <div className="mt-4 p-4 border rounded-xl bg-gray-50 space-y-3">
                                <div>
                                    <label className="block text-xs text-gray-500 mb-1">Importe</label>
                                    <input type="number" step="0.01" max={saldoPendiente} value={newPago.importe} onChange={e => setNewPago({ ...newPago, importe: e.target.value })} className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-[#1a365d]/20 text-sm" placeholder={`Máximo ${saldoPendiente}€`} />
                                </div>
                                <div>
                                    <label className="block text-xs text-gray-500 mb-1">Fecha de Cobro</label>
                                    <input type="date" value={newPago.fechaPago} onChange={e => setNewPago({ ...newPago, fechaPago: e.target.value })} className="w-full px-3 py-2 border rounded-lg outline-none focus:ring-2 focus:ring-[#1a365d]/20 text-sm" />
                                </div>
                                <div>
                                    <label className="block text-xs text-gray-500 mb-1">Método</label>
                                    <select value={newPago.metodoPago} onChange={e => setNewPago({ ...newPago, metodoPago: e.target.value })} className="w-full px-3 py-2 border rounded-lg outline-none bg-white text-sm">
                                        <option value="TRANSFERENCIA_BANCARIA">Transferencia</option>
                                        <option value="TARJETA">Tarjeta</option>
                                        <option value="EFECTIVO">Efectivo</option>
                                        <option value="RECIBO_DOMICILIADO">Recibo</option>
                                        <option value="PAGARE">Pagaré</option>
                                    </select>
                                </div>
                                <div className="flex gap-2 pt-2">
                                    <button onClick={handleAddPago} disabled={savingPago || !newPago.importe} className="flex-1 py-2 bg-[#1a365d] text-white rounded-lg text-sm hover:bg-[#2d4a7c] transition disabled:opacity-50">Guardar</button>
                                    <button onClick={() => setShowAddPago(false)} className="flex-1 py-2 border bg-white rounded-lg text-sm text-gray-600 hover:bg-gray-50">Cancelar</button>
                                </div>
                            </div>
                        )}

                        <div className="mt-6 space-y-3">
                            <h4 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">Historial de Cobros</h4>
                            {factura.pagos?.length > 0 ? (
                                factura.pagos.map((p: any) => (
                                    <div key={p.id} className="flex items-center justify-between p-3 border rounded-lg bg-green-50/30">
                                        <div>
                                            <p className="font-semibold text-green-700">{formatCurrency(p.importe)}</p>
                                            <p className="text-xs text-gray-500 mt-0.5">{new Date(p.fechaPago).toLocaleDateString('es-ES')} — {p.metodoPago.replace(/_/g, ' ')}</p>
                                        </div>
                                        {userRole === 'admin' && (
                                            <button onClick={() => handleDeletePago(p.id)} className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition" title="Eliminar pago">
                                                <Trash2 className="w-4 h-4" />
                                            </button>
                                        )}
                                    </div>
                                ))
                            ) : (
                                <p className="text-sm text-gray-400 text-center py-4 bg-gray-50 rounded-lg border border-dashed">No se han registrado pagos.</p>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
