'use client';

import React, { useState, useEffect } from 'react';
import AppListView, { AppDetailCard, AppTabs } from '@/components/layout/AppComponents';
import {
    User, Phone, Mail, MapPin, Calendar, CreditCard, BookOpen,
    Clock, Camera, Save, Trash2, X, Plus, Edit, RotateCcw,
    ChevronLeft, ChevronRight, CheckSquare, Info
} from 'lucide-react';
import { cn } from '@/lib/utils';

export default function AlumnosPage() {
    const [alumnos, setAlumnos] = useState<any[]>([]);
    const [filteredAlumnos, setFilteredAlumnos] = useState<any[]>([]);
    const [selectedAlumno, setSelectedAlumno] = useState<any>(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [showAll, setShowAll] = useState(false);
    const [activeTab, setActiveTab] = useState('estudios');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetch('/api/alumnos')
            .then(res => res.json())
            .then(data => {
                const list = Array.isArray(data) ? data : [];
                setAlumnos(list);
                setFilteredAlumnos(list.filter((a: any) => a.activo === 1));
                setLoading(false);
            });
    }, []);

    useEffect(() => {
        let filtered = alumnos.filter(a =>
            `${a.nombre} ${a.apellidos} ${a.nif}`.toLowerCase().includes(searchTerm.toLowerCase())
        );
        if (!showAll) {
            filtered = filtered.filter(a => a.activo === 1);
        }
        setFilteredAlumnos(filtered);
    }, [searchTerm, alumnos, showAll]);

    const tabs = [
        { id: 'estudios', label: 'Estudios/Notas' },
        { id: 'documentacion', 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 overflow-hidden -m-8 bg-[#f0f0f0]">
            {/* Lista Lateral */}
            <div className="w-full lg:w-80 flex-shrink-0 border-r border-border bg-white flex flex-col shadow-xl z-20">
                <div className="p-4 bg-slate-100 border-b border-border">
                    <label className="flex items-center space-x-2 cursor-pointer group">
                        <input
                            type="checkbox"
                            className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
                            checked={showAll}
                            onChange={() => setShowAll(!showAll)}
                        />
                        <span className="text-xs font-bold text-slate-600 uppercase">Ver Todos</span>
                    </label>
                </div>
                <AppListView
                    title="Alumnos"
                    items={filteredAlumnos}
                    onSearch={(term) => setSearchTerm(term)}
                    renderItem={(alumno) => (
                        <div
                            className={cn(
                                "p-3 cursor-pointer border-l-4 transition-all",
                                selectedAlumno?.id === alumno.id
                                    ? "bg-primary/10 border-primary"
                                    : "border-transparent hover:bg-slate-50"
                            )}
                            onClick={() => setSelectedAlumno(alumno)}
                        >
                            <div className="flex items-center space-x-3">
                                <div className="flex-1 min-w-0">
                                    <p className="text-xs font-bold truncate uppercase">{alumno.apellidos}, {alumno.nombre}</p>
                                    <p className="text-[10px] text-muted-foreground uppercase">{alumno.nif || 'Sin NIF'}</p>
                                </div>
                                {alumno.activo === 0 && (
                                    <span className="text-[8px] bg-red-100 text-red-600 px-1 rounded font-bold">BAJA</span>
                                )}
                            </div>
                        </div>
                    )}
                />
            </div>

            {/* Ficha Principal */}
            <div className="flex-1 overflow-y-auto flex flex-col">
                {/* Herramientas Superior - Estilo Delphi */}
                <div className="bg-white border-b border-border p-2 flex flex-wrap gap-1 sticky top-0 z-10 shadow-sm">
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-emerald-600 rounded transition-colors border border-transparent hover:border-slate-200">
                        <Plus className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Nuevo</span>
                    </button>
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-red-600 rounded transition-colors border border-transparent hover:border-slate-200">
                        <Trash2 className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Borrar</span>
                    </button>
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-blue-600 rounded transition-colors border border-transparent hover:border-slate-200">
                        <Edit className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Editar</span>
                    </button>
                    <div className="w-[1px] h-10 bg-slate-200 mx-2"></div>
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-slate-700 rounded transition-colors border border-transparent hover:border-slate-200">
                        <Save className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Guardar</span>
                    </button>
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-slate-700 rounded transition-colors border border-transparent hover:border-slate-200">
                        <X className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Cancelar</span>
                    </button>
                    <button className="flex flex-col items-center px-4 py-1 hover:bg-slate-50 text-slate-700 rounded transition-colors border border-transparent hover:border-slate-200 ml-auto">
                        <RotateCcw className="w-5 h-5 mb-0.5" />
                        <span className="text-[9px] font-bold uppercase">Actualizar</span>
                    </button>
                </div>

                {selectedAlumno ? (
                    <div className="p-4 space-y-4">
                        {/* Título de la sección */}
                        <div className="flex justify-center">
                            <h1 className="text-4xl font-black italic text-slate-800 tracking-tighter">Alumnos</h1>
                        </div>

                        {/* Bloques de Datos Superior */}
                        <div className="bg-[#fffde7] border border-[#fbc02d]/30 rounded shadow-sm p-4">
                            <div className="grid grid-cols-1 xl:grid-cols-4 gap-6">
                                {/* Datos Personales */}
                                <div className="xl:col-span-2 space-y-3">
                                    <div className="grid grid-cols-6 gap-2 items-center">
                                        <label className="text-[10px] font-bold text-right pr-2">ID</label>
                                        <input type="text" readOnly value={selectedAlumno.id} className="col-span-1 bg-white border border-slate-300 px-2 py-0.5 text-xs font-bold" />
                                        <label className="text-[10px] font-bold text-right pr-2">NIF</label>
                                        <input type="text" value={selectedAlumno.nif} className="col-span-3 bg-white border border-slate-300 px-2 py-0.5 text-xs" />
                                    </div>
                                    <div className="grid grid-cols-6 gap-2 items-center">
                                        <label className="text-[10px] font-bold text-right pr-2">Nombre</label>
                                        <input type="text" value={selectedAlumno.nombre} className="col-span-5 bg-white border border-slate-300 px-2 py-0.5 text-xs uppercase" />
                                    </div>
                                    <div className="grid grid-cols-6 gap-2 items-center">
                                        <label className="text-[10px] font-bold text-right pr-2">Apellidos</label>
                                        <input type="text" value={selectedAlumno.apellidos} className="col-span-5 bg-white border border-slate-300 px-2 py-0.5 text-xs uppercase" />
                                    </div>
                                    <div className="grid grid-cols-12 gap-2 items-center">
                                        <label className="col-span-3 text-[10px] font-bold text-right pr-2">F. Nacim.</label>
                                        <input type="date" value={selectedAlumno.f_nacimiento} className="col-span-4 bg-white border border-slate-300 px-2 py-0.5 text-xs" />
                                        <label className="col-span-2 text-[10px] font-bold text-right pr-2">Edad</label>
                                        <input type="text" readOnly value="16 años" className="col-span-3 bg-slate-100 border border-slate-300 px-2 py-0.5 text-xs font-bold" />
                                    </div>
                                    <div className="grid grid-cols-6 gap-2 items-center">
                                        <label className="text-[10px] font-bold text-right pr-2">Dirección</label>
                                        <input type="text" value={selectedAlumno.direccion} className="col-span-5 bg-white border border-slate-300 px-2 py-0.5 text-xs" />
                                    </div>
                                    <div className="grid grid-cols-9 gap-2 items-center">
                                        <label className="col-span-2 text-[10px] font-bold text-right pr-2">Cod. Postal</label>
                                        <input type="text" value={selectedAlumno.cp} className="col-span-2 bg-white border border-slate-300 px-2 py-0.5 text-xs" />
                                        <label className="col-span-1 text-[10px] font-bold text-right pr-2">Pobl.</label>
                                        <input type="text" value={selectedAlumno.poblacion} className="col-span-4 bg-white border border-slate-300 px-2 py-0.5 text-xs" />
                                    </div>
                                </div>

                                {/* Información Académica y Cliente */}
                                <div className="space-y-4">
                                    <div className="border border-slate-300 p-2 rounded bg-white/50 space-y-2">
                                        <p className="text-[9px] font-black uppercase text-slate-500 mb-1">Información Académica</p>
                                        <div className="flex flex-col space-y-1">
                                            <div className="flex items-center justify-between">
                                                <span className="text-[10px] font-bold">¿Alumno Actual?</span>
                                                <div className="flex bg-slate-200 rounded p-0.5 w-16 h-6">
                                                    <div className={cn("flex-1 text-[8px] flex items-center justify-center font-bold rounded", selectedAlumno.activo ? "bg-primary text-white" : "")}>SI</div>
                                                    <div className={cn("flex-1 text-[8px] flex items-center justify-center font-bold rounded", !selectedAlumno.activo ? "bg-red-500 text-white" : "")}>NO</div>
                                                </div>
                                            </div>
                                            <div className="flex items-center justify-between">
                                                <span className="text-[10px] font-bold">¿Generar recibos?</span>
                                                <div className="flex bg-slate-200 rounded p-0.5 w-16 h-6">
                                                    <div className="flex-1 text-[8px] flex items-center justify-center font-bold rounded bg-primary text-white">SI</div>
                                                    <div className="flex-1 text-[8px] flex items-center justify-center font-bold rounded">NO</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="border border-slate-300 p-2 rounded bg-white/50 space-y-2">
                                        <p className="text-[9px] font-black uppercase text-slate-500 mb-1">Datos de Cliente (Pagador)</p>
                                        <div className="space-y-1">
                                            <label className="text-[9px] font-bold">Nombre Cliente</label>
                                            <div className="flex gap-1">
                                                <input type="text" readOnly value="MARTÍNEZ BELDA, INMA" className="flex-1 bg-white border border-slate-300 px-2 py-0.5 text-[10px] font-bold" />
                                                <button className="bg-slate-100 border border-slate-300 px-1 rounded hover:bg-slate-200"><Info className="w-3 h-3" /></button>
                                            </div>
                                        </div>
                                        <div className="grid grid-cols-2 gap-2">
                                            <div>
                                                <label className="text-[9px] font-bold">Teléfono 1</label>
                                                <input type="text" readOnly value="677320676" className="w-full bg-slate-50 border border-slate-300 px-2 py-0.5 text-[10px]" />
                                            </div>
                                            <div>
                                                <label className="text-[9px] font-bold">Población</label>
                                                <input type="text" readOnly value="NOVELDA" className="w-full bg-slate-50 border border-slate-300 px-2 py-0.5 text-[10px]" />
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                {/* Foto */}
                                <div className="flex flex-col items-center space-y-2">
                                    <div className="w-40 h-48 bg-white border-2 border-slate-300 rounded shadow-inner overflow-hidden flex items-center justify-center relative group">
                                        {/* Simulación de foto */}
                                        <div className="w-full h-full bg-slate-200 flex items-center justify-center">
                                            <User className="w-20 h-20 text-slate-400" />
                                        </div>
                                        <div className="absolute bottom-0 left-0 right-0 p-1 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex justify-center space-x-2">
                                            <button className="text-white hover:text-primary"><ChevronLeft className="w-4 h-4" /></button>
                                            <button className="text-white hover:text-primary"><Plus className="w-4 h-4" /></button>
                                            <button className="text-white hover:text-primary"><Trash2 className="w-4 h-4" /></button>
                                            <button className="text-white hover:text-primary"><ChevronRight className="w-4 h-4" /></button>
                                        </div>
                                    </div>
                                    <button className="w-full bg-slate-100 border border-slate-300 py-1 rounded text-[10px] font-bold hover:bg-slate-200 uppercase tracking-tighter">Cargar imagen</button>
                                </div>
                            </div>

                            {/* Fila Inferior de Firmas y Mas */}
                            <div className="mt-4 grid grid-cols-1 lg:grid-cols-12 gap-4 items-end">
                                <div className="lg:col-span-4">
                                    <div className="flex items-center space-x-2 bg-emerald-100 p-2 rounded border border-emerald-200">
                                        <CheckSquare className="w-5 h-5 text-emerald-700" />
                                        <span className="text-[10px] font-black uppercase text-emerald-800">Permitir tratamiento de datos</span>
                                    </div>
                                </div>
                                <div className="lg:col-span-2">
                                    <label className="text-[9px] font-bold uppercase block mb-1">Descuento %</label>
                                    <input type="text" value="0" className="w-full bg-white border border-slate-300 px-2 py-1 text-xs font-bold text-center" />
                                </div>
                                <div className="lg:col-span-6">
                                    <label className="text-[9px] font-bold uppercase block mb-1">Observaciones Varias</label>
                                    <textarea rows={1} className="w-full bg-white border border-slate-300 px-2 py-1 text-xs resize-none"></textarea>
                                </div>
                            </div>
                        </div>

                        {/* Pestañas Inferiores */}
                        <div className="flex-1 flex flex-col min-h-[400px]">
                            <AppTabs tabs={tabs} activeTab={activeTab} onChange={setActiveTab} />
                            <div className="flex-1 bg-white border border-border border-t-0 p-4 shadow-inner">
                                {activeTab === 'estudios' && (
                                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 h-full">
                                        {/* Historial de Cursos */}
                                        <div className="border border-slate-200 rounded flex flex-col">
                                            <div className="bg-slate-100 p-2 border-b border-slate-200 flex gap-2">
                                                <button className="p-1 bg-white border border-slate-300 rounded hover:bg-blue-50 text-blue-600"><Plus className="w-4 h-4" /></button>
                                                <button className="p-1 bg-white border border-slate-300 rounded hover:bg-red-50 text-red-600"><Trash2 className="w-4 h-4" /></button>
                                            </div>
                                            <div className="overflow-auto max-h-[300px]">
                                                <table className="w-full text-[10px]">
                                                    <thead className="bg-slate-50 sticky top-0 border-b border-slate-200">
                                                        <tr>
                                                            <th className="px-2 py-1 text-left font-bold border-r">Curso</th>
                                                            <th className="px-2 py-1 text-left font-bold border-r">Grupo</th>
                                                            <th className="px-2 py-1 text-left font-bold border-r">Profesor</th>
                                                            <th className="px-2 py-1 text-center font-bold">F. Inicio</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody className="divide-y divide-slate-100">
                                                        <tr className="bg-blue-50/50">
                                                            <td className="px-2 py-1 border-r font-bold">2025-2026</td>
                                                            <td className="px-2 py-1 border-r text-primary">25 FCE1,2 (M5)</td>
                                                            <td className="px-2 py-1 border-r">SCOTT</td>
                                                            <td className="px-2 py-1 text-center font-mono">22/09/25</td>
                                                        </tr>
                                                        <tr className="hover:bg-slate-50">
                                                            <td className="px-2 py-1 border-r">2024-2025</td>
                                                            <td className="px-2 py-1 border-r">24 PET1.2 (L6)</td>
                                                            <td className="px-2 py-1 border-r">ROBERT</td>
                                                            <td className="px-2 py-1 text-center font-mono">15/09/24</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>

                                        {/* Evaluaciones */}
                                        <div className="bg-[#f8f9fa] border border-slate-200 rounded p-4 space-y-4">
                                            <div className="flex gap-2 mb-4 border-b border-slate-300 pb-2">
                                                <button className="px-3 py-1 bg-white border border-slate-300 rounded text-[10px] font-bold uppercase hover:bg-slate-100">Editar</button>
                                                <button className="px-3 py-1 bg-primary text-white rounded text-[10px] font-bold uppercase disabled:opacity-50" disabled>Guardar</button>
                                                <button className="px-3 py-1 bg-white border border-slate-300 rounded text-[10px] font-bold uppercase hover:bg-slate-100">Cancelar</button>
                                            </div>

                                            <div className="grid grid-cols-7 gap-1">
                                                {['Reading', 'Use English', 'Writing', 'Listening', 'Speaking', 'Developing', 'Media'].map(skill => (
                                                    <div key={skill} className="flex flex-col items-center">
                                                        <label className="text-[8px] font-bold uppercase text-slate-500 mb-1">{skill}</label>
                                                        <input type="text" className="w-full border border-slate-300 text-center py-1 text-xs font-bold" value="8" />
                                                    </div>
                                                ))}
                                            </div>

                                            <div className="space-y-2">
                                                <label className="text-[10px] font-bold uppercase text-slate-600 block">Observaciones Media</label>
                                                <div className="bg-white border border-slate-300 p-2 text-xs h-24 overflow-y-auto">
                                                    Neizan necesita traer el libro a clase y enfocarse. Es capaz de avanzar mucho más.
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                ) : (
                    <div className="flex-1 flex flex-col items-center justify-center text-slate-400 bg-white">
                        <User className="w-32 h-32 opacity-10 mb-4" />
                        <h2 className="text-xl font-bold text-slate-300 uppercase italic tracking-tighter">Seleccione un expediente</h2>
                    </div>
                )}
            </div>
        </div>
    );
}
