'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Users,
  Plus,
  ArrowLeft,
  LayoutGrid,
  Calendar,
  MapPin,
  Save,
  Trash2,
  User,
  GripVertical,
} from 'lucide-react';
import { toast } from 'sonner';

interface Alumno {
  id: string;
  categoria: string;
  posicionPrincipal?: string;
  posicionesSecundarias?: string[];
  usuario: {
    nombres: string;
    apellidos: string;
    foto?: string;
  };
}

interface Evento {
  id: string;
  descripcion: string;
  fecha: string;
  lugar?: string;
  categorias: string[];
  tipo: string;
  estado: string;
}

interface JugadorAlineacion {
  id: string;
  nombre: string;
  posicion: string;
  posicionCancha?: { x: number; y: number };
}

const FORMACIONES = [
  { value: '4-4-2', label: '4-4-2', posiciones: ['POR', 'DFC', 'DFC', 'LI', 'LD', 'MC', 'MC', 'MI', 'MD', 'DC', 'DC'] },
  { value: '4-3-3', label: '4-3-3', posiciones: ['POR', 'DFC', 'DFC', 'LI', 'LD', 'MC', 'MC', 'MC', 'EI', 'DC', 'ED'] },
  { value: '4-2-3-1', label: '4-2-3-1', posiciones: ['POR', 'DFC', 'DFC', 'LI', 'LD', 'MCD', 'MCD', 'MI', 'MCO', 'MD', 'DC'] },
  { value: '3-5-2', label: '3-5-2', posiciones: ['POR', 'DFC', 'DFC', 'DFC', 'MI', 'MC', 'MC', 'MC', 'MD', 'DC', 'DC'] },
  { value: '5-3-2', label: '5-3-2', posiciones: ['POR', 'DFC', 'DFC', 'DFC', 'LI', 'LD', 'MC', 'MC', 'MC', 'DC', 'DC'] },
  { value: '4-1-4-1', label: '4-1-4-1', posiciones: ['POR', 'DFC', 'DFC', 'LI', 'LD', 'MCD', 'MI', 'MC', 'MC', 'MD', 'DC'] },
];

// Posiciones en la cancha para cada formación (coordenadas relativas)
const POSICIONES_CANCHA: Record<string, { x: number; y: number }[]> = {
  '4-4-2': [
    { x: 50, y: 90 }, // POR
    { x: 35, y: 70 }, { x: 65, y: 70 }, // DFC
    { x: 15, y: 70 }, { x: 85, y: 70 }, // Laterales
    { x: 35, y: 45 }, { x: 65, y: 45 }, // MC
    { x: 15, y: 45 }, { x: 85, y: 45 }, // Extremos
    { x: 35, y: 20 }, { x: 65, y: 20 }, // DC
  ],
  '4-3-3': [
    { x: 50, y: 90 },
    { x: 35, y: 70 }, { x: 65, y: 70 },
    { x: 15, y: 70 }, { x: 85, y: 70 },
    { x: 30, y: 45 }, { x: 50, y: 45 }, { x: 70, y: 45 },
    { x: 15, y: 20 }, { x: 50, y: 20 }, { x: 85, y: 20 },
  ],
  '4-2-3-1': [
    { x: 50, y: 90 },
    { x: 35, y: 70 }, { x: 65, y: 70 },
    { x: 15, y: 70 }, { x: 85, y: 70 },
    { x: 35, y: 55 }, { x: 65, y: 55 },
    { x: 15, y: 35 }, { x: 50, y: 35 }, { x: 85, y: 35 },
    { x: 50, y: 15 },
  ],
  '3-5-2': [
    { x: 50, y: 90 },
    { x: 25, y: 70 }, { x: 50, y: 70 }, { x: 75, y: 70 },
    { x: 10, y: 45 }, { x: 30, y: 45 }, { x: 50, y: 45 }, { x: 70, y: 45 }, { x: 90, y: 45 },
    { x: 35, y: 20 }, { x: 65, y: 20 },
  ],
  '5-3-2': [
    { x: 50, y: 90 },
    { x: 25, y: 70 }, { x: 50, y: 70 }, { x: 75, y: 70 },
    { x: 10, y: 70 }, { x: 90, y: 70 },
    { x: 30, y: 45 }, { x: 50, y: 45 }, { x: 70, y: 45 },
    { x: 35, y: 20 }, { x: 65, y: 20 },
  ],
  '4-1-4-1': [
    { x: 50, y: 90 },
    { x: 35, y: 70 }, { x: 65, y: 70 },
    { x: 15, y: 70 }, { x: 85, y: 70 },
    { x: 50, y: 55 },
    { x: 15, y: 35 }, { x: 38, y: 35 }, { x: 62, y: 35 }, { x: 85, y: 35 },
    { x: 50, y: 15 },
  ],
};

export default function AlineacionesPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [eventos, setEventos] = useState<Evento[]>([]);
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCrearDialog, setShowCrearDialog] = useState(false);

  // Estado de la alineación
  const [selectedEvento, setSelectedEvento] = useState<string>('');
  const [formacion, setFormacion] = useState<string>('4-4-2');
  const [tipoCancha, setTipoCancha] = useState<string>('COMPLETA');
  const [jugadoresPorLado, setJugadoresPorLado] = useState<number>(11);
  const [titulares, setTitulares] = useState<JugadorAlineacion[]>([]);
  const [suplentes, setSuplentes] = useState<JugadorAlineacion[]>([]);
  const [alumnosDisponibles, setAlumnosDisponibles] = useState<Alumno[]>([]);
  const [draggedPlayer, setDraggedPlayer] = useState<{ alumno: Alumno; from: string } | null>(null);

  useEffect(() => {
    if (status === 'loading') return;
    if (!session) {
      router.push('/login');
      return;
    }
    if (!['COORDINADOR', 'PROFESOR'].includes(session.user?.rol || '')) {
      router.push('/dashboard');
      toast.error('No tienes permisos para acceder a esta sección');
      return;
    }
    fetchDatos();
  }, [session, status, router]);

  const fetchDatos = async () => {
    try {
      const [eventosRes, alumnosRes] = await Promise.all([
        fetch('/api/eventos?tipo=AMISTOSO&estado=PROGRAMADO'),
        fetch('/api/alumnos'),
      ]);
      const eventosData = await eventosRes.json();
      const alumnosData = await alumnosRes.json();

      // Incluir también eventos de campeonato
      const eventosCampeonato = await fetch('/api/eventos?tipo=CAMPEONATO&estado=PROGRAMADO');
      const campeonatoData = await eventosCampeonato.json();

      setEventos([...(eventosData.eventos || []), ...(campeonatoData.eventos || [])]);
      setAlumnos(alumnosData.alumnos || []);
    } catch (error) {
      console.error('Error:', error);
      toast.error('Error al cargar datos');
    } finally {
      setLoading(false);
    }
  };

  const handleEventoChange = (eventoId: string) => {
    setSelectedEvento(eventoId);
    const evento = eventos.find((e) => e.id === eventoId);
    if (evento) {
      // Filtrar alumnos por categoría del evento
      const alumnosFiltrados = alumnos.filter((a) =>
        evento.categorias.includes(a.categoria)
      );
      setAlumnosDisponibles(alumnosFiltrados);
      setTitulares([]);
      setSuplentes([]);
    }
  };

  const handleDragStart = (alumno: Alumno, from: string) => {
    setDraggedPlayer({ alumno, from });
  };

  const handleDropToTitulares = (posicionIndex: number) => {
    if (!draggedPlayer) return;

    const formacionActual = FORMACIONES.find((f) => f.value === formacion);
    const posicion = formacionActual?.posiciones[posicionIndex] || 'MC';
    const coords = POSICIONES_CANCHA[formacion]?.[posicionIndex];

    const nuevoJugador: JugadorAlineacion = {
      id: draggedPlayer.alumno.id,
      nombre: `${draggedPlayer.alumno.usuario.nombres} ${draggedPlayer.alumno.usuario.apellidos}`,
      posicion,
      posicionCancha: coords,
    };

    // Remover de su ubicación anterior
    if (draggedPlayer.from === 'disponibles') {
      setAlumnosDisponibles((prev) => prev.filter((a) => a.id !== draggedPlayer.alumno.id));
    } else if (draggedPlayer.from === 'suplentes') {
      setSuplentes((prev) => prev.filter((j) => j.id !== draggedPlayer.alumno.id));
    }

    // Si ya hay un jugador en esa posición, moverlo a disponibles
    const jugadorExistente = titulares[posicionIndex];
    if (jugadorExistente) {
      const alumnoExistente = alumnos.find((a) => a.id === jugadorExistente.id);
      if (alumnoExistente) {
        setAlumnosDisponibles((prev) => [...prev, alumnoExistente]);
      }
    }

    // Agregar a titulares
    const nuevosTitulares = [...titulares];
    nuevosTitulares[posicionIndex] = nuevoJugador;
    setTitulares(nuevosTitulares);
    setDraggedPlayer(null);
  };

  const handleDropToSuplentes = () => {
    if (!draggedPlayer) return;

    const nuevoJugador: JugadorAlineacion = {
      id: draggedPlayer.alumno.id,
      nombre: `${draggedPlayer.alumno.usuario.nombres} ${draggedPlayer.alumno.usuario.apellidos}`,
      posicion: draggedPlayer.alumno.posicionPrincipal || 'SUP',
    };

    if (draggedPlayer.from === 'disponibles') {
      setAlumnosDisponibles((prev) => prev.filter((a) => a.id !== draggedPlayer.alumno.id));
    } else if (draggedPlayer.from === 'titulares') {
      setTitulares((prev) => prev.filter((j) => j?.id !== draggedPlayer.alumno.id));
    }

    setSuplentes((prev) => [...prev, nuevoJugador]);
    setDraggedPlayer(null);
  };

  const handleDropToDisponibles = () => {
    if (!draggedPlayer || draggedPlayer.from === 'disponibles') return;

    const alumno = alumnos.find((a) => a.id === draggedPlayer.alumno.id);
    if (alumno) {
      setAlumnosDisponibles((prev) => [...prev, alumno]);
    }

    if (draggedPlayer.from === 'titulares') {
      setTitulares((prev) => prev.filter((j) => j?.id !== draggedPlayer.alumno.id));
    } else if (draggedPlayer.from === 'suplentes') {
      setSuplentes((prev) => prev.filter((j) => j.id !== draggedPlayer.alumno.id));
    }

    setDraggedPlayer(null);
  };

  const handleGuardarAlineacion = async () => {
    if (!selectedEvento) {
      toast.error('Selecciona un evento');
      return;
    }

    try {
      const res = await fetch('/api/alineaciones', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          eventoId: selectedEvento,
          tipo: eventos.find((e) => e.id === selectedEvento)?.tipo || 'AMISTOSO',
          tipoCancha,
          jugadoresPorLado,
          formacion,
          titulares: titulares.filter(Boolean),
          suplentes,
        }),
      });

      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.error || 'Error al guardar');
      }

      toast.success('Alineación guardada correctamente');
      setShowCrearDialog(false);
      // Reset
      setSelectedEvento('');
      setTitulares([]);
      setSuplentes([]);
      setAlumnosDisponibles([]);
    } catch (error) {
      console.error('Error:', error);
      toast.error(error instanceof Error ? error.message : 'Error al guardar alineación');
    }
  };

  if (status === 'loading' || loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-7xl">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.push('/dashboard')}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-3xl font-bold text-green-700 flex items-center gap-2">
              <LayoutGrid className="h-8 w-8" />
              Alineaciones
            </h1>
            <p className="text-muted-foreground">Crea formaciones tácticas para partidos</p>
          </div>
        </div>
        <Button
          onClick={() => setShowCrearDialog(true)}
          className="bg-green-600 hover:bg-green-700"
        >
          <Plus className="mr-2 h-4 w-4" />
          Nueva Alineación
        </Button>
      </div>

      {/* Dialog para crear alineación */}
      <Dialog open={showCrearDialog} onOpenChange={setShowCrearDialog}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Crear Alineación</DialogTitle>
          </DialogHeader>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Configuración */}
            <div className="space-y-4">
              <div>
                <Label>Evento</Label>
                <Select value={selectedEvento} onValueChange={handleEventoChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar evento..." />
                  </SelectTrigger>
                  <SelectContent>
                    {eventos.map((evento) => (
                      <SelectItem key={evento.id} value={evento.id}>
                        <div className="flex items-center gap-2">
                          <span>{evento.descripcion}</span>
                          <span className="text-xs text-muted-foreground">
                            {new Date(evento.fecha).toLocaleDateString('es-CL')}
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Formación</Label>
                <Select value={formacion} onValueChange={setFormacion}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {FORMACIONES.map((f) => (
                      <SelectItem key={f.value} value={f.value}>
                        {f.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>Tipo de Cancha</Label>
                <Select value={tipoCancha} onValueChange={setTipoCancha}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="COMPLETA">Cancha Completa (11)</SelectItem>
                    <SelectItem value="MEDIA">Media Cancha (7-9)</SelectItem>
                    <SelectItem value="CUARTO">Cuarto Cancha (5)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Jugadores Disponibles */}
              <div>
                <Label className="mb-2 block">Jugadores Disponibles ({alumnosDisponibles.length})</Label>
                <div
                  className="border rounded-lg p-3 min-h-[200px] max-h-[300px] overflow-y-auto bg-gray-50"
                  onDragOver={(e) => e.preventDefault()}
                  onDrop={handleDropToDisponibles}
                >
                  {alumnosDisponibles.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-4">
                      {selectedEvento
                        ? 'Todos los jugadores asignados'
                        : 'Selecciona un evento'}
                    </p>
                  ) : (
                    <div className="space-y-2">
                      {alumnosDisponibles.map((alumno) => (
                        <div
                          key={alumno.id}
                          draggable
                          onDragStart={() => handleDragStart(alumno, 'disponibles')}
                          className="flex items-center gap-2 p-2 bg-white rounded border cursor-move hover:border-green-500 hover:shadow-sm transition-all"
                        >
                          <GripVertical className="h-4 w-4 text-gray-400" />
                          <div className="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
                            <User className="h-4 w-4 text-green-700" />
                          </div>
                          <div className="flex-1">
                            <p className="text-sm font-medium">
                              {alumno.usuario.nombres} {alumno.usuario.apellidos}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {alumno.posicionPrincipal || 'Sin posición'} - Cat. {alumno.categoria}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Suplentes */}
              <div>
                <Label className="mb-2 block">Suplentes ({suplentes.length})</Label>
                <div
                  className="border rounded-lg p-3 min-h-[100px] bg-orange-50"
                  onDragOver={(e) => e.preventDefault()}
                  onDrop={handleDropToSuplentes}
                >
                  {suplentes.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-4">
                      Arrastra jugadores aquí
                    </p>
                  ) : (
                    <div className="flex flex-wrap gap-2">
                      {suplentes.map((jugador) => (
                        <div
                          key={jugador.id}
                          draggable
                          onDragStart={() =>
                            handleDragStart(
                              alumnos.find((a) => a.id === jugador.id)!,
                              'suplentes'
                            )
                          }
                          className="px-3 py-2 bg-orange-100 rounded-full text-sm cursor-move hover:bg-orange-200"
                        >
                          {jugador.nombre.split(' ')[0]}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Cancha */}
            <div className="lg:col-span-2">
              <Label className="mb-2 block">Cancha - Formación {formacion}</Label>
              <div
                className="relative w-full aspect-[2/3] bg-green-600 rounded-lg overflow-hidden"
                style={{
                  backgroundImage: `
                    linear-gradient(to bottom, transparent 49.5%, white 49.5%, white 50.5%, transparent 50.5%),
                    radial-gradient(circle at 50% 50%, transparent 8%, white 8%, white 8.5%, transparent 8.5%)
                  `,
                }}
              >
                {/* Líneas de la cancha */}
                <div className="absolute inset-4 border-2 border-white/50 rounded" />
                <div className="absolute top-4 left-1/2 -translate-x-1/2 w-40 h-16 border-2 border-white/50" />
                <div className="absolute bottom-4 left-1/2 -translate-x-1/2 w-40 h-16 border-2 border-white/50" />

                {/* Posiciones de jugadores */}
                {POSICIONES_CANCHA[formacion]?.map((pos, index) => {
                  const jugador = titulares[index];
                  return (
                    <div
                      key={index}
                      className="absolute transform -translate-x-1/2 -translate-y-1/2"
                      style={{ left: `${pos.x}%`, top: `${pos.y}%` }}
                      onDragOver={(e) => e.preventDefault()}
                      onDrop={() => handleDropToTitulares(index)}
                    >
                      {jugador ? (
                        <div
                          draggable
                          onDragStart={() =>
                            handleDragStart(
                              alumnos.find((a) => a.id === jugador.id)!,
                              'titulares'
                            )
                          }
                          className="w-14 h-14 rounded-full bg-white shadow-lg flex flex-col items-center justify-center cursor-move hover:scale-110 transition-transform"
                        >
                          <span className="text-xs font-bold text-green-700">
                            {jugador.posicion}
                          </span>
                          <span className="text-[10px] text-gray-600 truncate max-w-[50px]">
                            {jugador.nombre.split(' ')[0]}
                          </span>
                        </div>
                      ) : (
                        <div className="w-14 h-14 rounded-full border-2 border-dashed border-white/70 flex items-center justify-center">
                          <span className="text-xs text-white/70">
                            {FORMACIONES.find((f) => f.value === formacion)?.posiciones[index]}
                          </span>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Leyenda */}
              <div className="mt-4 flex items-center justify-between">
                <div className="text-sm text-muted-foreground">
                  Titulares: {titulares.filter(Boolean).length} /{' '}
                  {POSICIONES_CANCHA[formacion]?.length || 11}
                </div>
                <Button
                  onClick={handleGuardarAlineacion}
                  disabled={!selectedEvento || titulares.filter(Boolean).length === 0}
                  className="bg-green-600 hover:bg-green-700"
                >
                  <Save className="mr-2 h-4 w-4" />
                  Guardar Alineación
                </Button>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Lista de eventos sin alineación */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calendar className="h-5 w-5" />
            Próximos Partidos
          </CardTitle>
        </CardHeader>
        <CardContent>
          {eventos.length === 0 ? (
            <p className="text-center text-muted-foreground py-8">
              No hay partidos programados
            </p>
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {eventos.map((evento) => (
                <div
                  key={evento.id}
                  className="p-4 border rounded-lg hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between">
                    <div>
                      <span
                        className={`text-xs px-2 py-1 rounded ${
                          evento.tipo === 'CAMPEONATO'
                            ? 'bg-yellow-100 text-yellow-700'
                            : 'bg-blue-100 text-blue-700'
                        }`}
                      >
                        {evento.tipo}
                      </span>
                      <h3 className="font-semibold mt-2">{evento.descripcion}</h3>
                    </div>
                  </div>
                  <div className="mt-3 space-y-1 text-sm text-muted-foreground">
                    <p className="flex items-center gap-2">
                      <Calendar className="h-4 w-4" />
                      {new Date(evento.fecha).toLocaleDateString('es-CL', {
                        weekday: 'long',
                        day: 'numeric',
                        month: 'long',
                      })}
                    </p>
                    {evento.lugar && (
                      <p className="flex items-center gap-2">
                        <MapPin className="h-4 w-4" />
                        {evento.lugar}
                      </p>
                    )}
                    <p className="flex items-center gap-2">
                      <Users className="h-4 w-4" />
                      Categorías: {evento.categorias.join(', ')}
                    </p>
                  </div>
                  <Button
                    variant="outline"
                    className="w-full mt-4"
                    onClick={() => {
                      setSelectedEvento(evento.id);
                      handleEventoChange(evento.id);
                      setShowCrearDialog(true);
                    }}
                  >
                    <LayoutGrid className="mr-2 h-4 w-4" />
                    Crear Alineación
                  </Button>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
