'use client';

import { useState, useEffect } from 'react';
import { Plus, Download, CalendarCheck, Loader2, AlertCircle } from 'lucide-react';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

interface Props {
    clienteId: string;
    canEdit: boolean;
}

export default function ContratosMantenimientoTab({ clienteId, canEdit }: Props) {
    const [contratos, setContratos] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    const [showAdd, setShowAdd] = useState(false);
    const [saving, setSaving] = useState(false);
    const [newContrato, setNewContrato] = useState({
        descripcion: 'Contrato de Mantenimiento Preventivo',
        fechaInicio: '',
        fechaFin: '',
        periodicidadMes: 1,
    });

    const [generandoId, setGenerandoId] = useState<string | null>(null);

    const fetchContratos = async () => {
        setLoading(true);
        try {
            const res = await fetch(`/api/clientes/${clienteId}/contratos`);
            if (res.ok) {
                const data = await res.json();
                setContratos(data);
            } else {
                setError('Error al cargar contratos');
            }
        } catch {
            setError('Error de red');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchContratos();
    }, [clienteId]);

    const handleAddContrato = async () => {
        if (!newContrato.fechaInicio || !newContrato.fechaFin || !newContrato.descripcion) {
            alert("Rellena todos los campos");
            return;
        }

        setSaving(true);
        try {
            const res = await fetch(`/api/clientes/${clienteId}/contratos`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(newContrato),
            });

            if (res.ok) {
                setShowAdd(false);
                setNewContrato({
                    descripcion: 'Contrato de Mantenimiento Preventivo',
                    fechaInicio: '',
                    fechaFin: '',
                    periodicidadMes: 1,
                });
                fetchContratos();
            } else {
                const d = await res.json();
                alert(d.error || 'Error al guardar');
            }
        } catch (e) {
            alert('Error de conexión');
        } finally {
            setSaving(false);
        }
    };

    const handleDownloadPdf = (id: string) => {
        window.open(`/api/contratos/${id}/pdf`, '_blank');
    };

    const handleGenerarVisitas = async (id: string) => {
        if (!confirm('Esto creará automáticamente los eventos en la Agenda general según la periodicidad. ¿Estás seguro?')) return;

        setGenerandoId(id);
        try {
            const res = await fetch(`/api/contratos/${id}/generar-visitas`, {
                method: 'POST',
            });
            const data = await res.json();

            if (res.ok) {
                alert(data.message || 'Visitas generadas con éxito');
            } else {
                alert(data.error || 'Error al generar visitas');
            }
        } catch {
            alert('Error de conexión al generar visitas');
        } finally {
            setGenerandoId(null);
        }
    };

    if (loading) return <div className="p-8 justify-center flex"><Loader2 className="animate-spin text-gray-400 w-6 h-6" /></div>;

    return (
        <div className="space-y-4">
            {error && <div className="bg-red-50 text-red-600 p-3 rounded text-sm">{error}</div>}

            {canEdit && !showAdd && (
                <button onClick={() => setShowAdd(true)} className="text-sm text-[#1a365d] hover:underline flex items-center gap-1">
                    <Plus className="w-4 h-4" /> Nuevo Contrato
                </button>
            )}

            {showAdd && (
                <div className="border rounded-lg p-4 bg-blue-50 space-y-3">
                    <h4 className="font-medium text-blue-900 border-b border-blue-100 pb-2 mb-3">Nuevo Contrato</h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="sm:col-span-2">
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Título / Concepto</label>
                            <input value={newContrato.descripcion} onChange={e => setNewContrato({ ...newContrato, descripcion: e.target.value })} className="w-full px-3 py-2 text-sm border rounded-lg outline-none" placeholder="Descripción del mantenimiento" />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Fecha de Inicio</label>
                            <input type="date" value={newContrato.fechaInicio} onChange={e => setNewContrato({ ...newContrato, fechaInicio: e.target.value })} className="w-full px-3 py-2 text-sm border rounded-lg outline-none" />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Fecha de Fin</label>
                            <input type="date" value={newContrato.fechaFin} onChange={e => setNewContrato({ ...newContrato, fechaFin: e.target.value })} className="w-full px-3 py-2 text-sm border rounded-lg outline-none" />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Intervalo de Visitas</label>
                            <select value={newContrato.periodicidadMes} onChange={e => setNewContrato({ ...newContrato, periodicidadMes: Number(e.target.value) })} className="w-full px-3 py-2 text-sm border rounded-lg outline-none bg-white">
                                <option value={1}>Mensual (cada mes)</option>
                                <option value={2}>Bimestral (cada 2 meses)</option>
                                <option value={3}>Trimestral (cada 3 meses)</option>
                                <option value={6}>Semestral (cada 6 meses)</option>
                                <option value={12}>Anual (cada 12 meses)</option>
                            </select>
                        </div>
                    </div>
                    <div className="flex gap-2 mt-4 pt-2">
                        <button onClick={handleAddContrato} disabled={saving} className="px-4 py-2 text-sm bg-[#1a365d] text-white rounded-lg flex items-center gap-2">
                            {saving && <Loader2 className="w-4 h-4 animate-spin" />} Guardar Contrato
                        </button>
                        <button onClick={() => setShowAdd(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-200 rounded-lg">Cancelar</button>
                    </div>
                </div>
            )}

            {contratos.length === 0 ? (
                <p className="text-sm text-gray-400 text-center py-8">Vacio. No hay contratos registrados.</p>
            ) : (
                <div className="space-y-4">
                    {contratos.map((c) => (
                        <div key={c.id} className="border border-gray-200 rounded-xl bg-white overflow-hidden shadow-sm">
                            <div className="p-4 flex flex-col sm:flex-row sm:items-start justify-between gap-4">
                                <div className="space-y-2">
                                    <div className="flex items-center gap-2">
                                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${c.estado === 'ACTIVO' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}>{c.estado}</span>
                                        <span className="text-sm font-semibold text-gray-900">{c.descripcion}</span>
                                    </div>

                                    <div className="grid grid-cols-2 sm:flex sm:flex-row gap-x-6 gap-y-2 text-sm text-gray-600">
                                        <div>
                                            <span className="text-xs text-gray-400 block">Inicio</span>
                                            {format(new Date(c.fechaInicio), 'dd/MM/yyyy')}
                                        </div>
                                        <div>
                                            <span className="text-xs text-gray-400 block">Fin</span>
                                            {format(new Date(c.fechaFin), 'dd/MM/yyyy')}
                                        </div>
                                        <div>
                                            <span className="text-xs text-gray-400 block">Periodicidad</span>
                                            Cada {c.periodicidadMes} {c.periodicidadMes === 1 ? 'mes' : 'meses'}
                                        </div>
                                    </div>
                                </div>

                                <div className="flex flex-col sm:items-end gap-2 border-t sm:border-t-0 pt-3 sm:pt-0">
                                    <button
                                        onClick={() => handleDownloadPdf(c.id)}
                                        className="w-full sm:w-auto flex justify-center items-center gap-1.5 px-3 py-1.5 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-700 font-medium transition"
                                    >
                                        <Download className="w-4 h-4" /> PDF
                                    </button>

                                    {canEdit && c.estado === 'ACTIVO' && (
                                        <button
                                            onClick={() => handleGenerarVisitas(c.id)}
                                            disabled={generandoId === c.id}
                                            className="w-full sm:w-auto flex justify-center items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-50 text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-100 font-medium transition disabled:opacity-50"
                                        >
                                            {generandoId === c.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <CalendarCheck className="w-4 h-4" />} Generar Visitas
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
