'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 { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, Plus, Target, Edit, Trash2, CheckCircle } from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

interface Objetivo {
  id: string;
  tipo: 'TACTICO' | 'TECNICO' | 'PSICOLOGICO';
  objetivoFinal: string;
  objetivoInicial: string;
  objetivosIntermedios: string[];
  progreso: number;
  completado: boolean;
  fechaCreacion: string;
  fechaActualizacion: string;
  alumno: {
    usuario: {
      nombres: string;
      apellidos: string;
      nombreCorto: string;
    };
  };
  profesor: {
    nombres: string;
    apellidos: string;
  };
}

const TIPOS_OBJETIVO = {
  TACTICO: { label: 'Táctico', color: 'bg-blue-100 text-blue-800' },
  TECNICO: { label: 'Técnico', color: 'bg-green-100 text-green-800' },
  PSICOLOGICO: { label: 'Psicológico', color: 'bg-purple-100 text-purple-800' }
};

export default function ObjetivosPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [objetivos, setObjetivos] = useState<Objetivo[]>([]);
  const [filtroTipo, setFiltroTipo] = useState<string>('todos');
  const [filtroCompletado, setFiltroCompletado] = useState<string>('todos');

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin');
    }
  }, [status, router]);

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

  const fetchObjetivos = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/objetivos');
      if (response.ok) {
        const data = await response.json();
        setObjetivos(data.objetivos || []);
      }
    } catch (error) {
      toast.error('Error al cargar objetivos');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const response = await fetch(`/api/objetivos/${id}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        toast.success('Objetivo eliminado');
        fetchObjetivos();
      } else {
        toast.error('Error al eliminar objetivo');
      }
    } catch (error) {
      toast.error('Error de conexión');
    }
  };

  const handleUpdateProgress = async (id: string, nuevoProgreso: number) => {
    try {
      const response = await fetch(`/api/objetivos/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          progreso: nuevoProgreso,
          completado: nuevoProgreso >= 100
        })
      });

      if (response.ok) {
        toast.success('Progreso actualizado');
        fetchObjetivos();
      } else {
        toast.error('Error al actualizar progreso');
      }
    } catch (error) {
      toast.error('Error de conexión');
    }
  };

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

  const canCreate = session?.user?.rol === 'COORDINADOR' || session?.user?.rol === 'PROFESOR';

  const objetivosFiltrados = objetivos.filter(obj => {
    if (filtroTipo !== 'todos' && obj.tipo !== filtroTipo) return false;
    if (filtroCompletado === 'completados' && !obj.completado) return false;
    if (filtroCompletado === 'pendientes' && obj.completado) return false;
    return true;
  });

  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">
          <div className="flex items-center justify-between">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => router.push('/dashboard')}
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              Volver al Dashboard
            </Button>
            {canCreate && (
              <Button onClick={() => router.push('/dashboard/objetivos/nuevo')}>
                <Plus className="w-4 h-4 mr-2" />
                Nuevo Objetivo
              </Button>
            )}
          </div>
        </div>
      </header>

      {/* Content */}
      <div className="max-w-6xl mx-auto px-4 py-8">
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="flex items-center gap-2">
                  <Target className="w-5 h-5" />
                  Objetivos Individuales
                </CardTitle>
                <CardDescription>
                  Gestiona los objetivos personalizados de cada alumno
                </CardDescription>
              </div>
              <div className="flex gap-2">
                <Select value={filtroTipo} onValueChange={setFiltroTipo}>
                  <SelectTrigger className="w-[150px]">
                    <SelectValue placeholder="Tipo" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="todos">Todos los tipos</SelectItem>
                    <SelectItem value="TACTICO">Tácticos</SelectItem>
                    <SelectItem value="TECNICO">Técnicos</SelectItem>
                    <SelectItem value="PSICOLOGICO">Psicológicos</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={filtroCompletado} onValueChange={setFiltroCompletado}>
                  <SelectTrigger className="w-[150px]">
                    <SelectValue placeholder="Estado" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="todos">Todos</SelectItem>
                    <SelectItem value="pendientes">Pendientes</SelectItem>
                    <SelectItem value="completados">Completados</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {objetivosFiltrados.length === 0 ? (
              <div className="text-center py-12 text-gray-500">
                <Target className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>No hay objetivos registrados</p>
                {canCreate && (
                  <Button
                    variant="outline"
                    className="mt-4"
                    onClick={() => router.push('/dashboard/objetivos/nuevo')}
                  >
                    Crear primer objetivo
                  </Button>
                )}
              </div>
            ) : (
              <div className="space-y-4">
                {objetivosFiltrados.map((objetivo) => (
                  <div
                    key={objetivo.id}
                    className={`border rounded-lg p-4 ${
                      objetivo.completado ? 'bg-green-50 border-green-200' : 'bg-white'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <Badge className={TIPOS_OBJETIVO[objetivo.tipo].color}>
                            {TIPOS_OBJETIVO[objetivo.tipo].label}
                          </Badge>
                          {objetivo.completado && (
                            <Badge className="bg-green-500 text-white">
                              <CheckCircle className="w-3 h-3 mr-1" />
                              Completado
                            </Badge>
                          )}
                        </div>
                        <h3 className="font-semibold text-lg mb-1">
                          {objetivo.alumno?.usuario?.nombres} {objetivo.alumno?.usuario?.apellidos}
                        </h3>
                        <p className="text-gray-600 mb-3">
                          <strong>Objetivo Final:</strong> {objetivo.objetivoFinal}
                        </p>
                        
                        {/* Progreso */}
                        <div className="mb-3">
                          <div className="flex items-center justify-between text-sm mb-1">
                            <span>Progreso</span>
                            <span className="font-medium">{objetivo.progreso}%</span>
                          </div>
                          <Progress value={objetivo.progreso} className="h-2" />
                        </div>

                        {/* Detalles expandidos */}
                        <div className="text-sm text-gray-500 space-y-1">
                          <p><strong>Punto de partida:</strong> {objetivo.objetivoInicial}</p>
                          {objetivo.objetivosIntermedios?.length > 0 && (
                            <p>
                              <strong>Pasos intermedios:</strong> {objetivo.objetivosIntermedios.join(' → ')}
                            </p>
                          )}
                          <p>
                            <strong>Creado por:</strong> {objetivo.profesor?.nombres} {objetivo.profesor?.apellidos} |{' '}
                            {format(new Date(objetivo.fechaCreacion), "d 'de' MMMM yyyy", { locale: es })}
                          </p>
                        </div>
                      </div>

                      {/* Acciones */}
                      {canCreate && (
                        <div className="flex flex-col gap-2 ml-4">
                          {!objetivo.completado && (
                            <>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleUpdateProgress(objetivo.id, Math.min(objetivo.progreso + 25, 100))}
                              >
                                +25%
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                className="text-green-600"
                                onClick={() => handleUpdateProgress(objetivo.id, 100)}
                              >
                                <CheckCircle className="w-4 h-4" />
                              </Button>
                            </>
                          )}
                          <AlertDialog>
                            <AlertDialogTrigger asChild>
                              <Button size="sm" variant="outline" className="text-red-600">
                                <Trash2 className="w-4 h-4" />
                              </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                              <AlertDialogHeader>
                                <AlertDialogTitle>¿Eliminar objetivo?</AlertDialogTitle>
                                <AlertDialogDescription>
                                  Esta acción no se puede deshacer. Se eliminará permanentemente
                                  el objetivo del alumno.
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter>
                                <AlertDialogCancel>Cancelar</AlertDialogCancel>
                                <AlertDialogAction onClick={() => handleDelete(objetivo.id)}>
                                  Eliminar
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
