'use client';

import { useState } from 'react';
import { TIPO_EVENTO_BG } from '@/lib/agenda/constants';
import type { EventoAgenda } from './agenda-content';

interface Props {
  currentDate: Date;
  eventos: EventoAgenda[];
  loading: boolean;
  onDayClick: (date: Date) => void;
  onEventoClick: (eventoId: string) => void;
  onEventoMoved: (eventoId: string, newFecha: string, newTecnicoId?: string) => void;
  onAvisoDrop: (avisoId: string, fecha: string, tecnicoId?: string) => void;
}

const DIAS_HEADER = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];

function formatDateISO(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

function addDays(date: Date, days: number): Date {
  const d = new Date(date);
  d.setDate(d.getDate() + days);
  return d;
}

export default function AgendaMensual({
  currentDate, eventos, loading, onDayClick, onEventoClick, onEventoMoved, onAvisoDrop,
}: Props) {
  const [dragOverDay, setDragOverDay] = useState<string | null>(null);

  const year = currentDate.getFullYear();
  const month = currentDate.getMonth();
  const firstDayOfMonth = new Date(year, month, 1);
  const lastDayOfMonth = new Date(year, month + 1, 0);

  // Calculate grid start (Monday of the week containing the 1st)
  const firstDay = firstDayOfMonth.getDay();
  const startOffset = firstDay === 0 ? -6 : 1 - firstDay;
  const gridStart = addDays(firstDayOfMonth, startOffset);

  // 6 weeks
  const weeks: Date[][] = [];
  let current = new Date(gridStart);
  for (let w = 0; w < 6; w++) {
    const week: Date[] = [];
    for (let d = 0; d < 7; d++) {
      week.push(new Date(current));
      current = addDays(current, 1);
    }
    weeks.push(week);
  }

  const today = new Date();
  const todayISO = formatDateISO(today);

  const getEventosForDay = (fecha: string): EventoAgenda[] => {
    return eventos.filter(e => e.fecha.split('T')[0] === fecha);
  };

  const handleDragOver = (e: React.DragEvent, fecha: string) => {
    e.preventDefault();
    e.stopPropagation();
    const types = Array.from(e.dataTransfer.types);
    if (types.includes('application/aviso-id') || types.includes('application/evento-id') || types.includes('text/plain')) {
      e.dataTransfer.dropEffect = types.includes('application/aviso-id') ? 'copy' : 'move';
      setDragOverDay(fecha);
    }
  };

  const handleDrop = (e: React.DragEvent, fecha: string) => {
    e.preventDefault();
    e.stopPropagation();
    const avisoId = e.dataTransfer.getData('application/aviso-id');
    if (avisoId) {
      onAvisoDrop(avisoId, fecha);
    } else {
      const plainText = e.dataTransfer.getData('text/plain') || '';
      const eventoId = plainText.startsWith('evento:') ? plainText.replace('evento:', '') : e.dataTransfer.getData('application/evento-id');
      if (eventoId) onEventoMoved(eventoId, fecha);
    }
    setDragOverDay(null);
  };

  if (loading && eventos.length === 0) {
    return (
      <div className="bg-white rounded-xl border p-12 text-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#1a365d] mx-auto" />
        <p className="text-sm text-gray-500 mt-3">Cargando...</p>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl border overflow-hidden">
      {/* Day headers */}
      <div className="grid grid-cols-7 bg-gray-50 border-b">
        {DIAS_HEADER.map(d => (
          <div key={d} className="text-center text-xs font-semibold text-gray-500 uppercase py-2 border-r last:border-r-0">
            {d}
          </div>
        ))}
      </div>

      {/* Week rows */}
      {weeks.map((week, wi) => (
        <div key={wi} className="grid grid-cols-7 border-b last:border-b-0">
          {week.map((day, di) => {
            const fecha = formatDateISO(day);
            const isCurrentMonth = day.getMonth() === month;
            const isToday = fecha === todayISO;
            const dayEventos = getEventosForDay(fecha);
            const isDragOver = dragOverDay === fecha;

            return (
              <div
                key={di}
                className={`border-r last:border-r-0 min-h-[90px] p-1 cursor-pointer transition-colors ${!isCurrentMonth ? 'bg-gray-50/70' : ''
                  } ${isDragOver ? 'bg-blue-100 ring-2 ring-inset ring-blue-400' : ''} ${isToday ? 'bg-blue-50/50' : ''
                  } hover:bg-gray-50`}
                onClick={() => onDayClick(day)}
                onDragOver={(e) => handleDragOver(e, fecha)}
                onDragLeave={() => setDragOverDay(null)}
                onDrop={(e) => handleDrop(e, fecha)}
              >
                <div className={`text-right mb-1 ${isToday
                    ? 'inline-flex w-6 h-6 rounded-full bg-blue-600 text-white items-center justify-center text-xs font-bold float-right'
                    : `text-sm ${isCurrentMonth ? 'text-gray-800' : 'text-gray-300'}`
                  }`}>
                  {day.getDate()}
                </div>
                <div className="clear-both space-y-0.5">
                  {dayEventos.slice(0, 3).map(ev => {
                    const isAusencia = ev.tipo === 'AUSENCIA';
                    const isHistorico = (ev.estado === 'COMPLETADO' || ev.estado === 'CANCELADO') && !isAusencia;

                    let bg = isHistorico ? '#9ca3af' : (TIPO_EVENTO_BG[ev.tipo] || '#6b7280');
                    let stripeStyle = {};
                    if (isAusencia) {
                      if (ev.titulo.includes('Vacaciones')) {
                        bg = '#f59e0b'; stripeStyle = { backgroundImage: 'repeating-linear-gradient(45deg, #fef3c7, #fef3c7 7px, #fffbeb 7px, #fffbeb 14px)' };
                      } else if (ev.titulo.includes('Médica')) {
                        bg = '#ef4444'; stripeStyle = { backgroundImage: 'repeating-linear-gradient(45deg, #fee2e2, #fee2e2 7px, #fef2f2 7px, #fef2f2 14px)' };
                      } else {
                        bg = '#3b82f6'; stripeStyle = { backgroundImage: 'repeating-linear-gradient(45deg, #dbeafe, #dbeafe 7px, #eff6ff 7px, #eff6ff 14px)' };
                      }
                    }

                    return (
                      <div
                        key={ev.id}
                        onClick={(e) => { e.stopPropagation(); if (!isAusencia) onEventoClick(ev.id); }}
                        draggable={!isHistorico && !isAusencia}
                        onDragStart={(e) => {
                          if (isHistorico || isAusencia) return;
                          e.dataTransfer.setData('text/plain', `evento:${ev.id}`);
                          e.dataTransfer.setData('application/evento-id', ev.id);
                          e.dataTransfer.effectAllowed = 'move';
                        }}
                        className={`rounded px-1 py-0.5 text-[10px] truncate border-l-2 
                          ${!isAusencia ? 'cursor-pointer hover:shadow-sm' : 'cursor-default'} 
                          ${isHistorico ? 'opacity-70' : ''}`}
                        style={{ borderLeftColor: bg, backgroundColor: isHistorico ? '#f3f4f6' : (isAusencia ? undefined : `${bg}15`), color: isHistorico ? '#9ca3af' : bg, ...stripeStyle }}
                      >
                        {ev.horaInicio && !isAusencia && <span className="font-medium mr-0.5">{ev.horaInicio}</span>}
                        <span className={isHistorico ? 'text-gray-400' : 'text-gray-700'}>{ev.titulo}</span>
                      </div>
                    );
                  })}
                  {dayEventos.length > 3 && (
                    <div className="text-[10px] text-gray-400 pl-1">+{dayEventos.length - 3} más</div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}
