'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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import {
  ClipboardList,
  Plus,
  ArrowLeft,
  Calendar,
  MapPin,
  Users,
  Trophy,
  Target,
  AlertTriangle,
  Clock,
  User,
  ChevronRight,
  Edit,
  Trash2,
} from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

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

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

interface JugadorPartido {
  id: string;
  alumnoId: string;
  esTitular: boolean;
  posicion: string;
  numeroCamiseta?: number;
  minutosJugados: number;
  minutoEntrada?: number;
  minutoSalida?: number;
  alumno: {
    usuario: {
      nombres: string;
      apellidos: string;
      foto?: string;
    };
  };
}

interface GolPartido {
  id: string;
  alumnoId: string;
  minuto: number;
  tipoGol: string;
  asistenciaId?: string;
  alumno: {
    usuario: {
      nombres: string;
      apellidos: string;
    };
  };
}

interface TarjetaPartido {
  id: string;
  alumnoId: string;
  minuto: number;
  tipo: string;
  motivo?: string;
  alumno: {
    usuario: {
      nombres: string;
      apellidos: string;
    };
  };
}

interface FichaPartido {
  id: string;
  eventoId: string;
  categoria: string;
  rival: string;
  fecha: string;
  lugar: string;
  golesAFavor: number;
  golesEnContra: number;
  resultado: string;
  formacion: string;
  tipoPartido: string;
  observaciones?: string;
  jugadores: JugadorPartido[];
  goles: GolPartido[];
  tarjetas: TarjetaPartido[];
}

const FORMACIONES = ['4-4-2', '4-3-3', '4-2-3-1', '3-5-2', '5-3-2', '4-1-4-1'];
const POSICIONES = ['POR', 'DFC', 'LI', 'LD', 'MC', 'MCD', 'MCO', 'MI', 'MD', 'EI', 'ED', 'DC'];
const TIPOS_GOL = [
  { value: 'JUGADA', label: 'Jugada' },
  { value: 'PENAL', label: 'Penal' },
  { value: 'TIRO_LIBRE', label: 'Tiro Libre' },
  { value: 'CABEZA', label: 'Cabeza' },
  { value: 'AUTOGOL', label: 'Autogol' },
];

export default function FichasPartidoPage() {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const [fichas, setFichas] = useState<FichaPartido[]>([]);
  const [eventos, setEventos] = useState<Evento[]>([]);
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCrearDialog, setShowCrearDialog] = useState(false);
  const [showDetalleDialog, setShowDetalleDialog] = useState(false);
  const [selectedFicha, setSelectedFicha] = useState<FichaPartido | null>(null);
  const [showRegistrarGol, setShowRegistrarGol] = useState(false);
  const [showRegistrarTarjeta, setShowRegistrarTarjeta] = useState(false);

  // Estado del formulario de nueva ficha
  const [nuevaFicha, setNuevaFicha] = useState({
    eventoId: '',
    categoria: '',
    rival: '',
    fecha: '',
    lugar: '',
    formacion: '4-4-2',
    tipoPartido: 'AMISTOSO',
  });

  // Estado para jugadores seleccionados
  const [jugadoresSeleccionados, setJugadoresSeleccionados] = useState<
    { alumnoId: string; esTitular: boolean; posicion: string; numeroCamiseta?: number }[]
  >([]);

  // Estado para registrar gol/tarjeta
  const [nuevoGol, setNuevoGol] = useState({
    alumnoId: '',
    minuto: 0,
    tipoGol: 'JUGADA',
    asistenciaId: '',
  });

  const [nuevaTarjeta, setNuevaTarjeta] = useState({
    alumnoId: '',
    minuto: 0,
    tipo: 'AMARILLA',
    motivo: '',
  });

  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 [fichasRes, eventosRes, alumnosRes] = await Promise.all([
        fetch('/api/fichas-partido'),
        fetch('/api/eventos'),
        fetch('/api/alumnos'),
      ]);
      const fichasData = await fichasRes.json();
      const eventosData = await eventosRes.json();
      const alumnosData = await alumnosRes.json();

      setFichas(fichasData.fichas || []);
      // Filtrar solo eventos de tipo partido sin ficha
      const eventosPartido = (eventosData.eventos || []).filter(
        (e: Evento) =>
          (e.tipo === 'AMISTOSO' || e.tipo === 'CAMPEONATO') &&
          !fichasData.fichas?.some((f: FichaPartido) => f.eventoId === e.id)
      );
      setEventos(eventosPartido);
      setAlumnos(alumnosData.alumnos || []);
    } catch (error) {
      console.error('Error:', error);
      toast.error('Error al cargar datos');
    } finally {
      setLoading(false);
    }
  };

  const handleEventoChange = (eventoId: string) => {
    const evento = eventos.find((e) => e.id === eventoId);
    if (evento) {
      setNuevaFicha({
        ...nuevaFicha,
        eventoId,
        categoria: evento.categorias[0] || '',
        rival: evento.rival || '',
        fecha: evento.fecha.split('T')[0],
        lugar: evento.lugar || '',
        tipoPartido: evento.tipo,
      });
    }
  };

  const handleCrearFicha = async () => {
    try {
      const res = await fetch('/api/fichas-partido', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...nuevaFicha,
          jugadores: jugadoresSeleccionados,
        }),
      });

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

      toast.success('Ficha de partido creada');
      setShowCrearDialog(false);
      setNuevaFicha({
        eventoId: '',
        categoria: '',
        rival: '',
        fecha: '',
        lugar: '',
        formacion: '4-4-2',
        tipoPartido: 'AMISTOSO',
      });
      setJugadoresSeleccionados([]);
      fetchDatos();
    } catch (error) {
      console.error('Error:', error);
      toast.error(error instanceof Error ? error.message : 'Error al crear ficha');
    }
  };

  const handleRegistrarGol = async () => {
    if (!selectedFicha) return;
    try {
      const res = await fetch(`/api/fichas-partido/${selectedFicha.id}/goles`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(nuevoGol),
      });

      if (!res.ok) throw new Error('Error al registrar gol');

      toast.success('Gol registrado');
      setShowRegistrarGol(false);
      setNuevoGol({ alumnoId: '', minuto: 0, tipoGol: 'JUGADA', asistenciaId: '' });
      // Recargar ficha
      const fichaRes = await fetch(`/api/fichas-partido/${selectedFicha.id}`);
      const fichaData = await fichaRes.json();
      setSelectedFicha(fichaData.ficha);
      fetchDatos();
    } catch (error) {
      console.error('Error:', error);
      toast.error('Error al registrar gol');
    }
  };

  const handleRegistrarTarjeta = async () => {
    if (!selectedFicha) return;
    try {
      const res = await fetch(`/api/fichas-partido/${selectedFicha.id}/tarjetas`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(nuevaTarjeta),
      });

      if (!res.ok) throw new Error('Error al registrar tarjeta');

      toast.success('Tarjeta registrada');
      setShowRegistrarTarjeta(false);
      setNuevaTarjeta({ alumnoId: '', minuto: 0, tipo: 'AMARILLA', motivo: '' });
      // Recargar ficha
      const fichaRes = await fetch(`/api/fichas-partido/${selectedFicha.id}`);
      const fichaData = await fichaRes.json();
      setSelectedFicha(fichaData.ficha);
      fetchDatos();
    } catch (error) {
      console.error('Error:', error);
      toast.error('Error al registrar tarjeta');
    }
  };

  const handleActualizarResultado = async (golesEnContra: number) => {
    if (!selectedFicha) return;
    try {
      const res = await fetch(`/api/fichas-partido/${selectedFicha.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          golesAFavor: selectedFicha.golesAFavor,
          golesEnContra,
        }),
      });

      if (!res.ok) throw new Error('Error al actualizar');

      const fichaRes = await fetch(`/api/fichas-partido/${selectedFicha.id}`);
      const fichaData = await fichaRes.json();
      setSelectedFicha(fichaData.ficha);
      fetchDatos();
      toast.success('Resultado actualizado');
    } catch (error) {
      console.error('Error:', error);
      toast.error('Error al actualizar resultado');
    }
  };

  const toggleJugador = (alumnoId: string, esTitular: boolean) => {
    const existe = jugadoresSeleccionados.find((j) => j.alumnoId === alumnoId);
    if (existe) {
      setJugadoresSeleccionados((prev) => prev.filter((j) => j.alumnoId !== alumnoId));
    } else {
      const alumno = alumnos.find((a) => a.id === alumnoId);
      setJugadoresSeleccionados((prev) => [
        ...prev,
        {
          alumnoId,
          esTitular,
          posicion: alumno?.posicionPrincipal || 'MC',
        },
      ]);
    }
  };

  const getResultadoColor = (resultado: string) => {
    switch (resultado) {
      case 'VICTORIA':
        return 'bg-green-100 text-green-700';
      case 'EMPATE':
        return 'bg-yellow-100 text-yellow-700';
      case 'DERROTA':
        return 'bg-red-100 text-red-700';
      default:
        return 'bg-gray-100 text-gray-700';
    }
  };

  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>
    );
  }

  const alumnosFiltrados = nuevaFicha.categoria
    ? alumnos.filter((a) => a.categoria === nuevaFicha.categoria)
    : alumnos;

  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">
              <ClipboardList className="h-8 w-8" />
              Fichas de Partido
            </h1>
            <p className="text-muted-foreground">
              Registra partidos, goles, tarjetas y minutos jugados
            </p>
          </div>
        </div>
        <Button
          onClick={() => setShowCrearDialog(true)}
          className="bg-green-600 hover:bg-green-700"
          disabled={eventos.length === 0}
        >
          <Plus className="mr-2 h-4 w-4" />
          Nueva Ficha
        </Button>
      </div>

      {/* Lista de fichas */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {fichas.length === 0 ? (
          <Card className="col-span-full">
            <CardContent className="py-12 text-center">
              <ClipboardList className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No hay fichas de partido registradas</p>
            </CardContent>
          </Card>
        ) : (
          fichas.map((ficha) => (
            <Card
              key={ficha.id}
              className="cursor-pointer hover:shadow-lg transition-shadow"
              onClick={() => {
                setSelectedFicha(ficha);
                setShowDetalleDialog(true);
              }}
            >
              <CardHeader className="pb-2">
                <div className="flex items-start justify-between">
                  <div>
                    <Badge className={getResultadoColor(ficha.resultado)}>
                      {ficha.resultado}
                    </Badge>
                    <CardTitle className="mt-2 text-lg">
                      vs {ficha.rival}
                    </CardTitle>
                  </div>
                  <div className="text-2xl font-bold text-center">
                    <span className="text-green-600">{ficha.golesAFavor}</span>
                    <span className="text-gray-400 mx-1">-</span>
                    <span className="text-red-600">{ficha.golesEnContra}</span>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2 text-sm text-muted-foreground">
                  <p className="flex items-center gap-2">
                    <Calendar className="h-4 w-4" />
                    {format(new Date(ficha.fecha), "d 'de' MMMM yyyy", { locale: es })}
                  </p>
                  <p className="flex items-center gap-2">
                    <MapPin className="h-4 w-4" />
                    {ficha.lugar}
                  </p>
                  <p className="flex items-center gap-2">
                    <Users className="h-4 w-4" />
                    Categoría {ficha.categoria} - {ficha.formacion}
                  </p>
                </div>
                <div className="mt-4 flex items-center justify-between">
                  <div className="flex gap-4 text-sm">
                    <span className="flex items-center gap-1">
                      <Target className="h-4 w-4 text-green-600" />
                      {ficha.goles.length} goles
                    </span>
                    <span className="flex items-center gap-1">
                      <AlertTriangle className="h-4 w-4 text-yellow-600" />
                      {ficha.tarjetas.length} tarjetas
                    </span>
                  </div>
                  <ChevronRight className="h-5 w-5 text-muted-foreground" />
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      {/* Dialog crear ficha */}
      <Dialog open={showCrearDialog} onOpenChange={setShowCrearDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Nueva Ficha de Partido</DialogTitle>
          </DialogHeader>

          <Tabs defaultValue="info" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="info">Información</TabsTrigger>
              <TabsTrigger value="jugadores">Jugadores</TabsTrigger>
            </TabsList>

            <TabsContent value="info" className="space-y-4">
              <div>
                <Label>Evento</Label>
                <Select value={nuevaFicha.eventoId} onValueChange={handleEventoChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar evento..." />
                  </SelectTrigger>
                  <SelectContent>
                    {eventos.map((evento) => (
                      <SelectItem key={evento.id} value={evento.id}>
                        {evento.descripcion} -{' '}
                        {format(new Date(evento.fecha), 'dd/MM/yyyy')}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Rival</Label>
                  <Input
                    value={nuevaFicha.rival}
                    onChange={(e) => setNuevaFicha({ ...nuevaFicha, rival: e.target.value })}
                    placeholder="Nombre del rival"
                  />
                </div>
                <div>
                  <Label>Categoría</Label>
                  <Input value={nuevaFicha.categoria} readOnly className="bg-gray-50" />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Fecha</Label>
                  <Input
                    type="date"
                    value={nuevaFicha.fecha}
                    onChange={(e) => setNuevaFicha({ ...nuevaFicha, fecha: e.target.value })}
                  />
                </div>
                <div>
                  <Label>Lugar</Label>
                  <Input
                    value={nuevaFicha.lugar}
                    onChange={(e) => setNuevaFicha({ ...nuevaFicha, lugar: e.target.value })}
                    placeholder="Cancha / Estadio"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>Formación</Label>
                  <Select
                    value={nuevaFicha.formacion}
                    onValueChange={(v) => setNuevaFicha({ ...nuevaFicha, formacion: v })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {FORMACIONES.map((f) => (
                        <SelectItem key={f} value={f}>
                          {f}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Tipo</Label>
                  <Select
                    value={nuevaFicha.tipoPartido}
                    onValueChange={(v) => setNuevaFicha({ ...nuevaFicha, tipoPartido: v })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="AMISTOSO">Amistoso</SelectItem>
                      <SelectItem value="CAMPEONATO">Campeonato</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="jugadores">
              <div className="mb-4">
                <p className="text-sm text-muted-foreground">
                  Seleccionados: {jugadoresSeleccionados.length} jugadores
                  ({jugadoresSeleccionados.filter((j) => j.esTitular).length} titulares,{' '}
                  {jugadoresSeleccionados.filter((j) => !j.esTitular).length} suplentes)
                </p>
              </div>

              <div className="grid gap-2 max-h-[400px] overflow-y-auto">
                {alumnosFiltrados.map((alumno) => {
                  const seleccionado = jugadoresSeleccionados.find(
                    (j) => j.alumnoId === alumno.id
                  );
                  return (
                    <div
                      key={alumno.id}
                      className={`flex items-center justify-between p-3 rounded-lg border ${
                        seleccionado ? 'border-green-500 bg-green-50' : 'hover:bg-gray-50'
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                          <User className="h-5 w-5 text-green-700" />
                        </div>
                        <div>
                          <p className="font-medium">
                            {alumno.usuario.nombres} {alumno.usuario.apellidos}
                          </p>
                          <p className="text-sm text-muted-foreground">
                            {alumno.posicionPrincipal || 'Sin posición'}
                          </p>
                        </div>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant={seleccionado?.esTitular ? 'default' : 'outline'}
                          className={seleccionado?.esTitular ? 'bg-green-600' : ''}
                          onClick={() => toggleJugador(alumno.id, true)}
                        >
                          Titular
                        </Button>
                        <Button
                          size="sm"
                          variant={seleccionado && !seleccionado.esTitular ? 'default' : 'outline'}
                          className={
                            seleccionado && !seleccionado.esTitular ? 'bg-orange-500' : ''
                          }
                          onClick={() => toggleJugador(alumno.id, false)}
                        >
                          Suplente
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex justify-end gap-2 mt-4">
            <Button variant="outline" onClick={() => setShowCrearDialog(false)}>
              Cancelar
            </Button>
            <Button
              onClick={handleCrearFicha}
              disabled={!nuevaFicha.eventoId || !nuevaFicha.rival || jugadoresSeleccionados.length === 0}
              className="bg-green-600 hover:bg-green-700"
            >
              Crear Ficha
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Dialog detalle ficha */}
      <Dialog open={showDetalleDialog} onOpenChange={setShowDetalleDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          {selectedFicha && (
            <>
              <DialogHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <Badge className={getResultadoColor(selectedFicha.resultado)}>
                      {selectedFicha.resultado}
                    </Badge>
                    <DialogTitle className="mt-2">vs {selectedFicha.rival}</DialogTitle>
                    <p className="text-sm text-muted-foreground">
                      {format(new Date(selectedFicha.fecha), "d 'de' MMMM yyyy", { locale: es })} -{' '}
                      {selectedFicha.lugar}
                    </p>
                  </div>
                  <div className="text-4xl font-bold text-center">
                    <span className="text-green-600">{selectedFicha.golesAFavor}</span>
                    <span className="text-gray-400 mx-2">-</span>
                    <span className="text-red-600">{selectedFicha.golesEnContra}</span>
                  </div>
                </div>
              </DialogHeader>

              <Tabs defaultValue="jugadores" className="mt-4">
                <TabsList className="grid w-full grid-cols-3">
                  <TabsTrigger value="jugadores">Jugadores</TabsTrigger>
                  <TabsTrigger value="goles">Goles</TabsTrigger>
                  <TabsTrigger value="tarjetas">Tarjetas</TabsTrigger>
                </TabsList>

                <TabsContent value="jugadores" className="space-y-4">
                  <div>
                    <h4 className="font-semibold mb-2 flex items-center gap-2">
                      <Trophy className="h-4 w-4 text-green-600" />
                      Titulares ({selectedFicha.jugadores.filter((j) => j.esTitular).length})
                    </h4>
                    <div className="grid gap-2">
                      {selectedFicha.jugadores
                        .filter((j) => j.esTitular)
                        .map((jugador) => (
                          <div
                            key={jugador.id}
                            className="flex items-center justify-between p-2 bg-green-50 rounded"
                          >
                            <div className="flex items-center gap-2">
                              <span className="w-8 h-8 rounded-full bg-green-600 text-white flex items-center justify-center text-sm font-bold">
                                {jugador.numeroCamiseta || '-'}
                              </span>
                              <span>{jugador.alumno.usuario.nombres} {jugador.alumno.usuario.apellidos}</span>
                              <Badge variant="outline">{jugador.posicion}</Badge>
                            </div>
                            <span className="text-sm text-muted-foreground">
                              {jugador.minutosJugados}'
                            </span>
                          </div>
                        ))}
                    </div>
                  </div>

                  <div>
                    <h4 className="font-semibold mb-2 flex items-center gap-2">
                      <Users className="h-4 w-4 text-orange-600" />
                      Suplentes ({selectedFicha.jugadores.filter((j) => !j.esTitular).length})
                    </h4>
                    <div className="grid gap-2">
                      {selectedFicha.jugadores
                        .filter((j) => !j.esTitular)
                        .map((jugador) => (
                          <div
                            key={jugador.id}
                            className="flex items-center justify-between p-2 bg-orange-50 rounded"
                          >
                            <div className="flex items-center gap-2">
                              <span>{jugador.alumno.usuario.nombres} {jugador.alumno.usuario.apellidos}</span>
                              <Badge variant="outline">{jugador.posicion}</Badge>
                            </div>
                            <span className="text-sm text-muted-foreground">
                              {jugador.minutosJugados > 0 ? `${jugador.minutosJugados}'` : 'No ingresó'}
                            </span>
                          </div>
                        ))}
                    </div>
                  </div>
                </TabsContent>

                <TabsContent value="goles" className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h4 className="font-semibold">Goles a favor: {selectedFicha.golesAFavor}</h4>
                    <Button size="sm" onClick={() => setShowRegistrarGol(true)}>
                      <Plus className="mr-1 h-4 w-4" />
                      Registrar Gol
                    </Button>
                  </div>

                  {selectedFicha.goles.length === 0 ? (
                    <p className="text-center text-muted-foreground py-4">No hay goles registrados</p>
                  ) : (
                    <div className="space-y-2">
                      {selectedFicha.goles.map((gol) => (
                        <div key={gol.id} className="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
                          <div className="w-10 h-10 rounded-full bg-green-600 text-white flex items-center justify-center font-bold">
                            {gol.minuto}'
                          </div>
                          <div>
                            <p className="font-medium">
                              {gol.alumno.usuario.nombres} {gol.alumno.usuario.apellidos}
                            </p>
                            <p className="text-sm text-muted-foreground">{gol.tipoGol}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  <div className="border-t pt-4">
                    <Label>Goles en contra</Label>
                    <div className="flex items-center gap-2 mt-2">
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() =>
                          handleActualizarResultado(Math.max(0, selectedFicha.golesEnContra - 1))
                        }
                      >
                        -
                      </Button>
                      <span className="w-12 text-center text-xl font-bold">
                        {selectedFicha.golesEnContra}
                      </span>
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={() => handleActualizarResultado(selectedFicha.golesEnContra + 1)}
                      >
                        +
                      </Button>
                    </div>
                  </div>
                </TabsContent>

                <TabsContent value="tarjetas" className="space-y-4">
                  <div className="flex justify-between items-center">
                    <h4 className="font-semibold">Tarjetas: {selectedFicha.tarjetas.length}</h4>
                    <Button size="sm" onClick={() => setShowRegistrarTarjeta(true)}>
                      <Plus className="mr-1 h-4 w-4" />
                      Registrar Tarjeta
                    </Button>
                  </div>

                  {selectedFicha.tarjetas.length === 0 ? (
                    <p className="text-center text-muted-foreground py-4">
                      No hay tarjetas registradas
                    </p>
                  ) : (
                    <div className="space-y-2">
                      {selectedFicha.tarjetas.map((tarjeta) => (
                        <div
                          key={tarjeta.id}
                          className={`flex items-center gap-3 p-3 rounded-lg ${
                            tarjeta.tipo === 'ROJA' ? 'bg-red-50' : 'bg-yellow-50'
                          }`}
                        >
                          <div
                            className={`w-6 h-8 rounded ${
                              tarjeta.tipo === 'ROJA' ? 'bg-red-600' : 'bg-yellow-400'
                            }`}
                          />
                          <div className="flex-1">
                            <p className="font-medium">
                              {tarjeta.alumno.usuario.nombres} {tarjeta.alumno.usuario.apellidos}
                            </p>
                            <p className="text-sm text-muted-foreground">
                              Minuto {tarjeta.minuto}' {tarjeta.motivo && `- ${tarjeta.motivo}`}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* Dialog registrar gol */}
      <Dialog open={showRegistrarGol} onOpenChange={setShowRegistrarGol}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Registrar Gol</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Jugador</Label>
              <Select
                value={nuevoGol.alumnoId}
                onValueChange={(v) => setNuevoGol({ ...nuevoGol, alumnoId: v })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar..." />
                </SelectTrigger>
                <SelectContent>
                  {selectedFicha?.jugadores.map((j) => (
                    <SelectItem key={j.alumnoId} value={j.alumnoId}>
                      {j.alumno.usuario.nombres} {j.alumno.usuario.apellidos}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Minuto</Label>
                <Input
                  type="number"
                  value={nuevoGol.minuto}
                  onChange={(e) => setNuevoGol({ ...nuevoGol, minuto: parseInt(e.target.value) || 0 })}
                  min={0}
                  max={120}
                />
              </div>
              <div>
                <Label>Tipo</Label>
                <Select
                  value={nuevoGol.tipoGol}
                  onValueChange={(v) => setNuevoGol({ ...nuevoGol, tipoGol: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {TIPOS_GOL.map((t) => (
                      <SelectItem key={t.value} value={t.value}>
                        {t.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div>
              <Label>Asistencia (opcional)</Label>
              <Select
                value={nuevoGol.asistenciaId}
                onValueChange={(v) => setNuevoGol({ ...nuevoGol, asistenciaId: v })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Sin asistencia" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">Sin asistencia</SelectItem>
                  {selectedFicha?.jugadores
                    .filter((j) => j.alumnoId !== nuevoGol.alumnoId)
                    .map((j) => (
                      <SelectItem key={j.alumnoId} value={j.alumnoId}>
                        {j.alumno.usuario.nombres} {j.alumno.usuario.apellidos}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
            <Button onClick={handleRegistrarGol} className="w-full bg-green-600 hover:bg-green-700">
              Registrar Gol
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Dialog registrar tarjeta */}
      <Dialog open={showRegistrarTarjeta} onOpenChange={setShowRegistrarTarjeta}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Registrar Tarjeta</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Jugador</Label>
              <Select
                value={nuevaTarjeta.alumnoId}
                onValueChange={(v) => setNuevaTarjeta({ ...nuevaTarjeta, alumnoId: v })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar..." />
                </SelectTrigger>
                <SelectContent>
                  {selectedFicha?.jugadores.map((j) => (
                    <SelectItem key={j.alumnoId} value={j.alumnoId}>
                      {j.alumno.usuario.nombres} {j.alumno.usuario.apellidos}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Minuto</Label>
                <Input
                  type="number"
                  value={nuevaTarjeta.minuto}
                  onChange={(e) =>
                    setNuevaTarjeta({ ...nuevaTarjeta, minuto: parseInt(e.target.value) || 0 })
                  }
                  min={0}
                  max={120}
                />
              </div>
              <div>
                <Label>Tipo</Label>
                <Select
                  value={nuevaTarjeta.tipo}
                  onValueChange={(v) => setNuevaTarjeta({ ...nuevaTarjeta, tipo: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="AMARILLA">Amarilla</SelectItem>
                    <SelectItem value="ROJA">Roja</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div>
              <Label>Motivo (opcional)</Label>
              <Input
                value={nuevaTarjeta.motivo}
                onChange={(e) => setNuevaTarjeta({ ...nuevaTarjeta, motivo: e.target.value })}
                placeholder="Falta, protesta, etc."
              />
            </div>
            <Button
              onClick={handleRegistrarTarjeta}
              className={`w-full ${
                nuevaTarjeta.tipo === 'ROJA'
                  ? 'bg-red-600 hover:bg-red-700'
                  : 'bg-yellow-500 hover:bg-yellow-600'
              }`}
            >
              Registrar Tarjeta
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
