'use client';

import React, { useState, useEffect } from 'react';
import AppListView, { AppDetailCard, AppTabs } from '@/components/layout/AppComponents';
import { Building, Phone, Mail, MapPin, Globe, CreditCard, Users, FileText, Plus, Trash2, Save, X, Briefcase } from 'lucide-react';
import { cn } from '@/lib/utils';

export default function EmpresasPage() {
    const [empresas, setEmpresas] = useState<any[]>([]);
    const [filteredEmpresas, setFilteredEmpresas] = useState<any[]>([]);
    const [selectedEmpresa, setSelectedEmpresa] = useState<any>(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [recibos, setRecibos] = useState<any[]>([]);
    const [activeTab, setActiveTab] = useState('datos');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetch('/api/empresas')
            .then(res => res.json())
            .then(data => {
                const list = Array.isArray(data) ? data : [];
                setEmpresas(list);
                setFilteredEmpresas(list);
                setLoading(false);
            });
    }, []);

    useEffect(() => {
        const filtered = empresas.filter(e =>
            `${e.nombre} ${e.cif} ${e.poblacion}`.toLowerCase().includes(searchTerm.toLowerCase())
        );
        setFilteredEmpresas(filtered);
    }, [searchTerm, empresas]);

    const fetchRecibos = async (empresaId: number) => {
        const res = await fetch(`/api/empresas/${empresaId}/recibos`);
        const data = await res.json();
        setRecibos(data);
    };

    useEffect(() => {
        if (selectedEmpresa) {
            fetchRecibos(selectedEmpresa.id);
        }
    }, [selectedEmpresa]);

    const tabs = [
        { id: 'datos', label: 'Datos Fiscales' },
        { id: 'alumnos', label: 'Alumnos Vinculados' },
        { id: 'recibos', label: 'Recibos / Facturación' },
        { id: 'documentos', label: 'Documentación' },
    ];

    if (loading) return <div className="p-8">Cargando...</div>;

    return (
        <div className="flex h-[calc(100vh-2rem)] flex-col lg:flex-row shadow-sm overflow-hidden -m-8">
            {/* Lista de Empresas */}
            <div className="w-full lg:w-80 flex-shrink-0 border-r border-border bg-slate-50 overflow-hidden flex flex-col">
                <AppListView
                    title="Clientes / Empresas"
                    items={filteredEmpresas}
                    onSearch={(term) => setSearchTerm(term)}
                    onAdd={() => { }}
                    renderItem={(empresa) => (
                        <div
                            className={`p-4 cursor-pointer transition-colors ${selectedEmpresa?.id === empresa.id ? 'bg-primary/5 border-l-4 border-primary' : ''}`}
                            onClick={() => setSelectedEmpresa(empresa)}
                        >
                            <div className="flex items-center space-x-3">
                                <div className="h-10 w-10 rounded-lg bg-indigo-100 flex items-center justify-center font-bold text-indigo-600">
                                    <Building className="h-5 w-5" />
                                </div>
                                <div className="flex-1 min-w-0">
                                    <p className="text-sm font-semibold truncate uppercase">{empresa.nombre}</p>
                                    <p className="text-xs text-muted-foreground truncate">{empresa.cif}</p>
                                </div>
                            </div>
                        </div>
                    )}
                />
            </div>

            {/* Detalle de la Empresa */}
            <div className="flex-1 overflow-y-auto bg-white flex flex-col">
                {selectedEmpresa ? (
                    <>
                        <div className="p-4 border-b border-border bg-slate-50 flex flex-wrap gap-2 items-center justify-between sticky top-0 z-10">
                            <div className="flex gap-2">
                                <button className="flex items-center px-3 py-1.5 bg-white border border-border rounded text-sm font-medium hover:bg-slate-100 transition-colors">
                                    <Plus className="w-4 h-4 mr-1.5 text-emerald-600" /> Nuevo
                                </button>
                                <button className="flex items-center px-3 py-1.5 bg-white border border-border rounded text-sm font-medium hover:bg-slate-100 transition-colors">
                                    <Trash2 className="w-4 h-4 mr-1.5 text-red-600" /> Borrar
                                </button>
                                <button className="flex items-center px-3 py-1.5 bg-primary text-primary-foreground rounded text-sm font-medium hover:bg-primary/90 transition-colors">
                                    <Save className="w-4 h-4 mr-1.5" /> Guardar
                                </button>
                            </div>
                            <button className="lg:hidden p-2 text-muted-foreground" onClick={() => setSelectedEmpresa(null)}>
                                <X className="h-6 w-6" />
                            </button>
                        </div>

                        <div className="p-4 md:p-8 space-y-6">
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                                <div className="lg:col-span-2 space-y-6">
                                    <AppDetailCard title="Identificación Fiscal" color="yellow">
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Nombre Comercial</label>
                                                <p className="text-sm font-semibold uppercase">{selectedEmpresa.nombre}</p>
                                            </div>
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">CIF/NIE</label>
                                                <p className="text-sm font-semibold">{selectedEmpresa.cif}</p>
                                            </div>
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Razón Social</label>
                                                <p className="text-sm">{selectedEmpresa.razon_social || selectedEmpresa.nombre}</p>
                                            </div>
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Población</label>
                                                <p className="text-sm font-semibold flex items-center">
                                                    <MapPin className="w-3 h-3 mr-1.5" /> {selectedEmpresa.poblacion}
                                                </p>
                                            </div>
                                        </div>
                                    </AppDetailCard>

                                    <AppDetailCard title="Localización y Web" color="blue">
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div className="space-y-1 md:col-span-2">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Dirección Completa</label>
                                                <p className="text-sm">{selectedEmpresa.direccion}</p>
                                            </div>
                                            <div className="flex items-center space-x-2">
                                                <div className="p-1.5 bg-blue-100 rounded text-blue-600"><Globe className="w-4 h-4" /></div>
                                                <div>
                                                    <p className="text-[10px] uppercase text-muted-foreground font-bold">Sitio Web</p>
                                                    <p className="text-sm font-medium">{selectedEmpresa.web || 'No disponible'}</p>
                                                </div>
                                            </div>
                                            <div className="flex items-center space-x-2">
                                                <div className="p-1.5 bg-blue-100 rounded text-blue-600"><Mail className="w-4 h-4" /></div>
                                                <div>
                                                    <p className="text-[10px] uppercase text-muted-foreground font-bold">Email Corporativo</p>
                                                    <p className="text-sm font-medium truncate">{selectedEmpresa.email}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </AppDetailCard>
                                </div>

                                <div className="space-y-6">
                                    <div className="p-6 bg-slate-900 text-white rounded-xl shadow-lg relative overflow-hidden group">
                                        <div className="relative z-10">
                                            <div className="flex items-center justify-between mb-8">
                                                <Briefcase className="h-8 w-8 text-primary" />
                                                <div className="h-10 w-16 bg-white/10 rounded-lg backdrop-blur-md border border-white/20"></div>
                                            </div>
                                            <p className="text-[10px] font-bold text-white/50 uppercase tracking-widest mb-1">IBAN / Cuenta</p>
                                            <p className="text-lg font-mono tracking-wider mb-6 truncate">{selectedEmpresa.cc || '**** **** **** ****'}</p>
                                            <div className="flex justify-between items-end">
                                                <div>
                                                    <p className="text-[10px] font-bold text-white/50 uppercase mb-1">Entidad</p>
                                                    <p className="text-sm font-semibold">{selectedEmpresa.entidad || 'N/A'}</p>
                                                </div>
                                                <p className="text-right text-xs font-bold text-primary">FORMA PAGO</p>
                                            </div>
                                        </div>
                                        <div className="absolute top-0 right-0 -mr-8 -mt-8 h-32 w-32 bg-primary/20 rounded-full blur-2xl group-hover:bg-primary/30 transition-colors"></div>
                                    </div>

                                    <div className="p-4 bg-amber-50 border border-amber-100 rounded-xl">
                                        <h4 className="text-xs font-bold text-amber-800 uppercase mb-3 flex items-center">
                                            <Users className="w-4 h-4 mr-2" /> Representante / Contacto
                                        </h4>
                                        <p className="text-sm font-semibold text-amber-950 uppercase">{selectedEmpresa.representante || 'Sin asignar'}</p>
                                        <div className="mt-3 flex items-center text-xs text-amber-700">
                                            <Phone className="w-3 h-3 mr-1.5" /> {selectedEmpresa.telefono1}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="space-y-4">
                                <AppTabs tabs={tabs} activeTab={activeTab} onChange={setActiveTab} />
                                <div className="bg-slate-50 rounded-xl border border-border p-6 min-h-[200px]">
                                    {activeTab === 'datos' && (
                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Teléfono Empresa</label>
                                                <p className="text-sm">{selectedEmpresa.telefono1}</p>
                                            </div>
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Segundo Teléfono</label>
                                                <p className="text-sm">{selectedEmpresa.telefono2 || '-'}</p>
                                            </div>
                                            <div className="space-y-1">
                                                <label className="text-[10px] font-bold text-muted-foreground uppercase">Nº Empleados</label>
                                                <p className="text-sm">No definido</p>
                                            </div>
                                        </div>
                                    )}
                                    {activeTab === 'alumnos' && (
                                        <div className="text-center py-12 text-muted-foreground flex flex-col items-center">
                                            <Users className="w-12 h-12 mb-3 opacity-20" />
                                            <p>Esta empresa no tiene alumnos asociados actualmente.</p>
                                        </div>
                                    )}
                                    {activeTab === 'recibos' && (
                                        <div className="overflow-x-auto -m-6">
                                            <table className="w-full text-sm text-left">
                                                <thead className="bg-slate-100 text-[10px] uppercase font-bold text-muted-foreground border-b border-border">
                                                    <tr>
                                                        <th className="px-6 py-3">Fecha</th>
                                                        <th className="px-6 py-3">Concepto</th>
                                                        <th className="px-6 py-3 text-right">Importe</th>
                                                        <th className="px-6 py-3 text-right">Entrega</th>
                                                        <th className="px-6 py-3 text-center">Estado</th>
                                                    </tr>
                                                </thead>
                                                <tbody className="divide-y divide-border/50">
                                                    {recibos.map((recibo) => (
                                                        <tr key={recibo.id} className="hover:bg-slate-50 transition-colors">
                                                            <td className="px-6 py-4 font-medium">{new Date(recibo.fecharecibo).toLocaleDateString()}</td>
                                                            <td className="px-6 py-4 uppercase text-xs">{recibo.concepto}</td>
                                                            <td className="px-6 py-4 text-right font-bold text-slate-900">{recibo.importe}€</td>
                                                            <td className="px-6 py-4 text-right text-emerald-600 font-medium">{recibo.entrega}€</td>
                                                            <td className="px-6 py-4 text-center">
                                                                <span className={cn(
                                                                    "px-2 py-1 rounded text-[10px] font-bold border",
                                                                    recibo.pagado
                                                                        ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                                                                        : "bg-red-50 text-red-700 border-red-200"
                                                                )}>
                                                                    {recibo.pagado ? "PAGADO" : "PENDIENTE"}
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                    {recibos.length === 0 && (
                                                        <tr>
                                                            <td colSpan={5} className="px-6 py-12 text-center text-muted-foreground">
                                                                <CreditCard className="w-10 h-10 mx-auto mb-2 opacity-10" />
                                                                No hay recibos registrados para este cliente.
                                                            </td>
                                                        </tr>
                                                    )}
                                                </tbody>
                                            </table>
                                        </div>
                                    )}
                                    {activeTab === 'documentos' && (
                                        <div className="text-center py-12 text-muted-foreground flex flex-col items-center">
                                            <FileText className="w-12 h-12 mb-3 opacity-20" />
                                            <p>No se han digitalizado documentos para esta empresa.</p>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </>
                ) : (
                    <div className="flex-1 flex flex-col items-center justify-center p-12 text-center text-slate-400">
                        <Building className="h-16 w-16 mb-4 opacity-20" />
                        <h3 className="text-xl font-bold text-slate-900 mb-2">Ficha de Cliente / Empresa</h3>
                        <p className="max-w-xs text-sm">Seleccione una entidad para gestionar sus datos fiscales, alumnos matriculados y documentación asociada.</p>
                    </div>
                )}
            </div>
        </div>
    );
}
