'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,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Save, Target, Plus, X } from 'lucide-react';
import { toast } from 'sonner';

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

const TIPOS_OBJETIVO = [
  { value: 'TACTICO', label: 'Táctico', description: 'Posicionamiento, lectura del juego, decisiones' },
  { value: 'TECNICO', label: 'Técnico', description: 'Control, pase, regate, disparo' },
  { value: 'PSICOLOGICO', label: 'Psicológico', description: 'Confianza, concentración, motivación' }
];

export default function NuevoObjetivoPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [alumnos, setAlumnos] = useState<Alumno[]>([]);
  
  const [formData, setFormData] = useState({
    alumnoId: '',
    tipo: '',
    objetivoInicial: '',
    objetivoFinal: '',
    objetivosIntermedios: ['', '', ''] // Máximo 3
  });

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    } else if (status === 'authenticated') {
      if (session?.user?.rol !== 'COORDINADOR' && session?.user?.rol !== 'PROFESOR') {
        toast.error('No tienes permisos para crear objetivos');
        router.push('/dashboard');
      }
    }
  }, [status, session, router]);

  useEffect(() => {
    fetchAlumnos();
  }, []);

  const fetchAlumnos = async () => {
    try {
      const response = await fetch('/api/alumnos');
      if (response.ok) {
        const data = await response.json();
        setAlumnos(data.alumnos || []);
      }
    } catch (error) {
      toast.error('Error al cargar alumnos');
    }
  };

  const updateObjetivoIntermedio = (index: number, value: string) => {
    const nuevos = [...formData.objetivosIntermedios];
    nuevos[index] = value;
    setFormData({ ...formData, objetivosIntermedios: nuevos });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.alumnoId || !formData.tipo || !formData.objetivoInicial || !formData.objetivoFinal) {
      toast.error('Por favor completa todos los campos obligatorios');
      return;
    }

    setLoading(true);
    try {
      // Filtrar objetivos intermedios vacíos
      const objetivosIntermediosLimpios = formData.objetivosIntermedios.filter(o => o.trim() !== '');
      
      const response = await fetch('/api/objetivos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          alumnoId: formData.alumnoId,
          tipo: formData.tipo,
          objetivoInicial: formData.objetivoInicial,
          objetivoFinal: formData.objetivoFinal,
          objetivosIntermedios: objetivosIntermediosLimpios
        })
      });

      if (response.ok) {
        toast.success('Objetivo creado exitosamente');
        router.push('/dashboard/objetivos');
      } else {
        const error = await response.json();
        toast.error(error.error || 'Error al crear objetivo');
      }
    } catch (error) {
      toast.error('Error de conexión');
    } finally {
      setLoading(false);
    }
  };

  if (status === 'loading') {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-lg">Cargando...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => router.push('/dashboard/objetivos')}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            Volver a Objetivos
          </Button>
        </div>
      </header>

      {/* Content */}
      <div className="max-w-3xl mx-auto px-4 py-8">
        <form onSubmit={handleSubmit}>
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Target className="w-5 h-5" />
                Nuevo Objetivo Individual
              </CardTitle>
              <CardDescription>
                Define un objetivo personalizado para el desarrollo del alumno
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Selector de Alumno */}
              <div className="space-y-2">
                <Label>Alumno *</Label>
                <Select
                  value={formData.alumnoId}
                  onValueChange={(value) => setFormData({ ...formData, alumnoId: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Selecciona un alumno..." />
                  </SelectTrigger>
                  <SelectContent>
                    {alumnos.map((alumno) => (
                      <SelectItem key={alumno.id} value={alumno.id}>
                        {alumno.usuario.nombres} {alumno.usuario.apellidos} ({alumno.categoria})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Tipo de Objetivo */}
              <div className="space-y-2">
                <Label>Tipo de Objetivo *</Label>
                <Select
                  value={formData.tipo}
                  onValueChange={(value) => setFormData({ ...formData, tipo: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Selecciona el tipo..." />
                  </SelectTrigger>
                  <SelectContent>
                    {TIPOS_OBJETIVO.map((tipo) => (
                      <SelectItem key={tipo.value} value={tipo.value}>
                        <div>
                          <span className="font-medium">{tipo.label}</span>
                          <span className="text-gray-500 ml-2">- {tipo.description}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Punto de Partida */}
              <div className="space-y-2">
                <Label htmlFor="objetivoInicial">Punto de Partida (Situación Actual) *</Label>
                <Textarea
                  id="objetivoInicial"
                  placeholder="Describe la situación actual del alumno en este aspecto..."
                  value={formData.objetivoInicial}
                  onChange={(e) => setFormData({ ...formData, objetivoInicial: e.target.value })}
                  rows={3}
                />
                <p className="text-xs text-gray-500">
                  Ejemplo: "El alumno tiene dificultades para mantener su posición en la defensa durante los partidos"
                </p>
              </div>

              {/* Objetivo Final */}
              <div className="space-y-2">
                <Label htmlFor="objetivoFinal">Objetivo Final (Meta a Alcanzar) *</Label>
                <Textarea
                  id="objetivoFinal"
                  placeholder="Describe el objetivo que se quiere lograr..."
                  value={formData.objetivoFinal}
                  onChange={(e) => setFormData({ ...formData, objetivoFinal: e.target.value })}
                  rows={3}
                />
                <p className="text-xs text-gray-500">
                  Ejemplo: "Que el alumno mantenga correctamente su posición en la línea defensiva durante todo el partido"
                </p>
              </div>

              {/* Objetivos Intermedios */}
              <div className="space-y-4">
                <div>
                  <Label>Pasos Intermedios (Opcional - Máximo 3)</Label>
                  <p className="text-xs text-gray-500">
                    Define los pasos que el alumno debe cumplir para alcanzar el objetivo final
                  </p>
                </div>
                {formData.objetivosIntermedios.map((objetivo, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <div className="flex items-center justify-center w-8 h-8 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">
                      {index + 1}
                    </div>
                    <Input
                      placeholder={`Paso ${index + 1}...`}
                      value={objetivo}
                      onChange={(e) => updateObjetivoIntermedio(index, e.target.value)}
                    />
                  </div>
                ))}
              </div>

              {/* Vista Previa */}
              {(formData.objetivoInicial || formData.objetivoFinal) && (
                <div className="bg-gray-50 p-4 rounded-lg border">
                  <h4 className="font-medium mb-2">Vista Previa del Plan</h4>
                  <div className="flex items-center gap-2 text-sm">
                    <div className="bg-yellow-100 text-yellow-800 px-2 py-1 rounded">
                      Inicio
                    </div>
                    <span className="text-gray-400">→</span>
                    {formData.objetivosIntermedios.filter(o => o.trim()).map((_, idx) => (
                      <>
                        <div key={idx} className="bg-blue-100 text-blue-800 px-2 py-1 rounded">
                          Paso {idx + 1}
                        </div>
                        <span className="text-gray-400">→</span>
                      </>
                    ))}
                    <div className="bg-green-100 text-green-800 px-2 py-1 rounded">
                      Meta
                    </div>
                  </div>
                </div>
              )}

              {/* Botones */}
              <div className="flex items-center gap-4 pt-4">
                <Button type="submit" disabled={loading}>
                  <Save className="w-4 h-4 mr-2" />
                  {loading ? 'Guardando...' : 'Crear Objetivo'}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => router.push('/dashboard/objetivos')}
                  disabled={loading}
                >
                  Cancelar
                </Button>
              </div>
            </CardContent>
          </Card>
        </form>
      </div>
    </div>
  );
}
