'use client';

import { useState, useEffect, useCallback } from 'react';
import { Calendar, Loader2, Download, Plus, Trash2, X, Save, Flag } from 'lucide-react';
import { COMUNIDADES_AUTONOMAS, AMBITO_FESTIVO_LABELS } from '@/lib/configuracion/constants';

interface Festivo {
  id: string;
  fecha: string;
  nombre: string;
  ambito: string;
  comunidadAutonoma: string | null;
  municipio: string | null;
  anio: number;
}

export default function FestivosTab() {
  const [festivos, setFestivos] = useState<Festivo[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingAuto, setLoadingAuto] = useState(false);
  const [showManual, setShowManual] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [filterAmbito, setFilterAmbito] = useState('');
  const [anio] = useState(2026);
  const [configCcaa, setConfigCcaa] = useState('');

  const [manualForm, setManualForm] = useState({
    fecha: '',
    nombre: '',
    ambito: 'LOCAL',
    municipio: '',
  });

  const fetchFestivos = useCallback(async () => {
    try {
      let url = `/api/configuracion/festivos?anio=${anio}`;
      if (filterAmbito) url += `&ambito=${filterAmbito}`;
      const res = await fetch(url);
      const data = await res.json();
      if (data.success) setFestivos(data.festivos);
    } catch (err) {
      console.error('Error cargando festivos:', err);
    } finally {
      setLoading(false);
    }
  }, [anio, filterAmbito]);

  const fetchConfig = useCallback(async () => {
    try {
      const res = await fetch('/api/configuracion');
      const data = await res.json();
      if (data.success && data.config?.comunidadAutonoma) {
        setConfigCcaa(data.config.comunidadAutonoma);
      }
    } catch (err) {
      console.error('Error cargando config:', err);
    }
  }, []);

  useEffect(() => { fetchConfig(); }, [fetchConfig]);
  useEffect(() => { fetchFestivos(); }, [fetchFestivos]);

  const handleCargarAutomaticos = async () => {
    setLoadingAuto(true);
    setError('');
    setSuccessMsg('');
    try {
      const res = await fetch('/api/configuracion/festivos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          cargarAutomaticos: true,
          anio,
          comunidadAutonoma: configCcaa || undefined,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSuccessMsg(`${data.count} festivos cargados correctamente`);
        setTimeout(() => setSuccessMsg(''), 4000);
        fetchFestivos();
      } else {
        setError(data.error || 'Error cargando festivos');
      }
    } catch (err) {
      console.error('Error:', err);
      setError('Error de conexión');
    } finally {
      setLoadingAuto(false);
    }
  };

  const handleManualSubmit = async () => {
    if (!manualForm.fecha || !manualForm.nombre) {
      setError('Fecha y nombre son obligatorios');
      return;
    }
    setSaving(true);
    setError('');
    try {
      const res = await fetch('/api/configuracion/festivos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fecha: manualForm.fecha,
          nombre: manualForm.nombre,
          ambito: manualForm.ambito,
          municipio: manualForm.municipio,
          comunidadAutonoma: configCcaa || '',
        }),
      });
      const data = await res.json();
      if (data.success) {
        setShowManual(false);
        setManualForm({ fecha: '', nombre: '', ambito: 'LOCAL', municipio: '' });
        fetchFestivos();
      } else {
        setError(data.error || 'Error creando festivo');
      }
    } catch (err) {
      console.error('Error:', err);
      setError('Error de conexión');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('¿Eliminar este festivo?')) return;
    try {
      await fetch(`/api/configuracion/festivos/${id}`, { method: 'DELETE' });
      fetchFestivos();
    } catch (err) {
      console.error('Error eliminando:', err);
    }
  };

  const [syncing, setSyncing] = useState(false);

  const handleAplicarEnAgenda = async () => {
    if (festivos.length === 0) {
      setError('No hay festivos cargados para aplicar');
      return;
    }
    setSyncing(true);
    setError('');
    setSuccessMsg('');
    try {
      const payload = {
        anio,
        feriados: festivos.map(f => ({
          date: f.fecha.split('T')[0], // YYYY-MM-DD
          name: f.nombre,
        }))
      };
      const res = await fetch('/api/agenda/festivos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();
      if (res.ok) {
        setSuccessMsg(data.message || 'Festivos bloqueados en la agenda');
        setTimeout(() => setSuccessMsg(''), 4000);
      } else {
        setError(data.error || 'Error aplicando en la agenda');
      }
    } catch (err) {
      setError('Error de conexión a la agenda');
    } finally {
      setSyncing(false);
    }
  };

  const handleEliminarGlobal = async () => {
    if (!confirm(`¿Estás seguro de que deseas eliminar TODOS los festivos globales de la agenda del año ${anio}?`)) return;
    setSyncing(true);
    setError('');
    setSuccessMsg('');
    try {
      const res = await fetch(`/api/agenda/festivos?anio=${anio}`, { method: 'DELETE' });
      const data = await res.json();
      if (res.ok) {
        setSuccessMsg(data.message || 'Festivos purgados de la agenda');
        setTimeout(() => setSuccessMsg(''), 4000);
      } else {
        setError(data.error || 'Error purgando festivos');
      }
    } catch (err) {
      setError('Error de conexión a la agenda');
    } finally {
      setSyncing(false);
    }
  };

  const formatDate = (d: string) => {
    const date = new Date(d);
    return date.toLocaleDateString('es-ES', { weekday: 'short', day: '2-digit', month: 'short' });
  };

  const ambitoColor = (a: string) => {
    if (a === 'NACIONAL') return 'bg-red-100 text-red-700';
    if (a === 'AUTONOMICO') return 'bg-blue-100 text-blue-700';
    return 'bg-green-100 text-green-700';
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-xl border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <Calendar className="w-5 h-5 text-[#1a365d]" />
            <h3 className="text-lg font-semibold text-gray-900">Festivos {anio}</h3>
            <span className="text-sm text-gray-400">({festivos.length} días)</span>
          </div>
          <div className="flex flex-col sm:flex-row gap-2">
            <div className="flex bg-gray-100 rounded-lg p-1 mr-2">
              <button onClick={handleAplicarEnAgenda} disabled={syncing} className="px-3 py-1.5 text-xs font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50 transition-colors flex items-center gap-1">
                {syncing ? <Loader2 className="w-3 h-3 animate-spin" /> : <Calendar className="w-3 h-3" />} Insertar Festivos a la Agenda
              </button>
              <button onClick={handleEliminarGlobal} disabled={syncing} className="px-3 py-1.5 ml-1 text-xs font-semibold text-red-600 hover:bg-red-200 rounded-md transition-colors flex items-center gap-1">
                <Trash2 className="w-3 h-3" /> Eliminar Global
              </button>
            </div>
            <button
              onClick={handleCargarAutomaticos}
              disabled={loadingAuto}
              className="flex items-center gap-2 px-3 py-2 border border-gray-300 rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50 transition"
            >
              {loadingAuto ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
              Cargar nacionales{configCcaa ? ' + autonómicos' : ''}
            </button>
            <button
              onClick={() => { setShowManual(true); setError(''); }}
              className="flex items-center gap-2 px-3 py-2 bg-[#1a365d] text-white rounded-lg text-sm font-medium hover:bg-[#2d4a7c] transition"
            >
              <Plus className="w-4 h-4" />
              Añadir local
            </button>
          </div>
        </div>

        {successMsg && (
          <div className="text-sm text-green-700 bg-green-50 p-3 rounded-lg mb-4">{successMsg}</div>
        )}
        {error && !showManual && (
          <div className="text-sm text-red-600 bg-red-50 p-3 rounded-lg mb-4">{error}</div>
        )}

        {!configCcaa && (
          <div className="text-sm text-amber-700 bg-amber-50 p-3 rounded-lg mb-4">
            <Flag className="w-4 h-4 inline mr-1" />
            No has configurado la Comunidad Autónoma en la pestaña General. Solo se cargarán los festivos nacionales.
          </div>
        )}

        {/* Filtros */}
        <div className="flex gap-2 mb-4">
          <button
            onClick={() => setFilterAmbito('')}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition ${!filterAmbito ? 'bg-[#1a365d] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
          >
            Todos
          </button>
          {Object.entries(AMBITO_FESTIVO_LABELS).map(([key, label]) => (
            <button
              key={key}
              onClick={() => setFilterAmbito(key)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition ${filterAmbito === key ? 'bg-[#1a365d] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            >
              {label}
            </button>
          ))}
        </div>

        {/* Lista */}
        {festivos.length === 0 ? (
          <div className="text-center py-8 text-gray-400">
            <Calendar className="w-10 h-10 mx-auto mb-2 opacity-50" />
            <p>No hay festivos cargados</p>
            <p className="text-xs">Usa "Cargar nacionales" para importar los festivos del BOE</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {festivos.map((f) => (
              <div key={f.id} className="flex items-center justify-between py-2.5 px-2 hover:bg-gray-50 rounded-lg">
                <div className="flex items-center gap-3">
                  <span className="text-sm font-mono text-gray-500 w-28">{formatDate(f.fecha)}</span>
                  <span className="text-sm font-medium text-gray-900">{f.nombre}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${ambitoColor(f.ambito)}`}>
                    {AMBITO_FESTIVO_LABELS[f.ambito] || f.ambito}
                  </span>
                  {f.comunidadAutonoma && f.ambito === 'AUTONOMICO' && (
                    <span className="text-xs text-gray-400">{COMUNIDADES_AUTONOMAS[f.comunidadAutonoma]}</span>
                  )}
                  {f.municipio && f.ambito === 'LOCAL' && (
                    <span className="text-xs text-gray-400">{f.municipio}</span>
                  )}
                </div>
                <button
                  onClick={() => handleDelete(f.id)}
                  className="p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Modal festivo manual */}
      {showManual && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-md w-full">
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="font-semibold text-gray-900">Añadir festivo local</h3>
              <button onClick={() => setShowManual(false)} className="p-1 hover:bg-gray-100 rounded-lg">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              {error && <div className="text-sm text-red-600 bg-red-50 p-2 rounded-lg">{error}</div>}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Fecha *</label>
                <input
                  type="date"
                  value={manualForm.fecha}
                  onChange={(e) => setManualForm({ ...manualForm, fecha: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d]"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Nombre *</label>
                <input
                  type="text"
                  value={manualForm.nombre}
                  onChange={(e) => setManualForm({ ...manualForm, nombre: e.target.value })}
                  placeholder="Ej: Fiestas patronales de Torrent"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d]"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Municipio</label>
                <input
                  type="text"
                  value={manualForm.municipio}
                  onChange={(e) => setManualForm({ ...manualForm, municipio: e.target.value })}
                  placeholder="Ej: Torrent"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d]"
                />
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t">
              <button
                onClick={() => setShowManual(false)}
                className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition"
              >
                Cancelar
              </button>
              <button
                onClick={handleManualSubmit}
                disabled={saving}
                className="flex items-center gap-2 px-4 py-2 bg-[#1a365d] text-white rounded-lg text-sm font-medium hover:bg-[#2d4a7c] disabled:opacity-50 transition"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                Añadir festivo
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
