'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Edit,
  Eye,
  EyeOff,
  Trash2,
  FileText,
  Search,
  RefreshCw,
  Sparkles,
} from 'lucide-react';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/EmptyState';
import type { ExerciseType, ExerciseDifficulty } from '@/types';

interface Exercise {
  id: string;
  moduleId: string;
  module?: { name: string };
  type: ExerciseType;
  difficulty: ExerciseDifficulty;
  statement: string;
  correctAnswer: string;
  isPublished: boolean;
  isAIGenerated: boolean;
  points: number;
  order: number;
  createdAt: string;
}

export default function AdminExercisesPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(true);
  const [exercises, setExercises] = useState<Exercise[]>([]);
  const [modules, setModules] = useState<{ id: string; name: string }[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterPublished, setFilterPublished] = useState<'all' | 'published' | 'unpublished'>('all');
  const [filterModule, setFilterModule] = useState<string>('all');
  const [filterDifficulty, setFilterDifficulty] = useState<string>('all');

  useEffect(() => {
    void fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchData = async () => {
    try {
      setIsLoading(true);
      const exercisesData = await api.get<{ data: Exercise[] }>(
        apiEndpoints.exercises.list + '?isPublished=false'
      );
      const exercisesList = Array.isArray(exercisesData) ? exercisesData : ((exercisesData as Record<string, unknown>)['data'] as Exercise[]) || [];
      setExercises(exercisesList);

      const modulesData = await api.get<{ data: { id: string; name: string }[] }>(
        apiEndpoints.modules.list
      );
      const modulesList = Array.isArray(modulesData) ? modulesData : ((modulesData as Record<string, unknown>)['data'] as { id: string; name: string }[]) || [];
      setModules(modulesList);
    } catch (error) {
      toast({
        title: 'Error al cargar ejercicios',
        description: error instanceof Error ? error.message : 'No se pudo cargar los ejercicios',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleTogglePublish = (_exerciseId: string) => {
    toast({
      title: 'Funcionalidad pendiente',
      description: 'El endpoint para publicar/despublicar ejercicios aún no está implementado.',
    });
  };

  const filteredExercises = exercises.filter(exercise => {
    const matchesSearch = exercise.statement.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesPublished = filterPublished === 'all' ||
      (filterPublished === 'published' && exercise.isPublished) ||
      (filterPublished === 'unpublished' && !exercise.isPublished);
    const matchesModule = filterModule === 'all' || exercise.moduleId === filterModule;
    const matchesDifficulty = filterDifficulty === 'all' || exercise.difficulty === filterDifficulty;
    return matchesSearch && matchesPublished && matchesModule && matchesDifficulty;
  });

  const getDifficultyColor = (difficulty: ExerciseDifficulty) => {
    switch (difficulty) {
      case 'EASY':
        return 'bg-green-500/10 text-green-600 border-green-500/20';
      case 'MEDIUM':
        return 'bg-yellow-500/10 text-yellow-600 border-yellow-500/20';
      case 'HARD':
        return 'bg-red-500/10 text-red-600 border-red-500/20';
      default:
        return 'bg-gray-500/10 text-gray-600 border-gray-500/20';
    }
  };

  const getTypeLabel = (type: ExerciseType) => {
    switch (type) {
      case 'MULTIPLE_CHOICE':
        return 'Opción múltiple';
      case 'OPEN_ENDED':
        return 'Respuesta abierta';
      case 'TRUE_FALSE':
        return 'V/F';
      case 'CALCULATION':
        return 'Calculación';
      default:
        return type;
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <Skeleton className="h-8 w-48" />
            <Skeleton className="h-4 w-64 mt-2" />
          </div>
          <Skeleton className="h-10 w-40" />
        </div>
        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              {[1, 2, 3, 4, 5].map(i => (
                <Skeleton key={i} className="h-16 w-full" />
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Gestión de Ejercicios</h1>
          <p className="text-muted-foreground">Administra los ejercicios de la plataforma</p>
        </div>
        <Button onClick={() => router.push('/admin/generate')}>
            <Sparkles className="mr-2 h-4 w-4" />
            Generar con IA
          </Button>
      </div>

      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                type="text"
                placeholder="Buscar ejercicios..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pl-10 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
              />
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <select
                value={filterModule}
                onChange={(e) => setFilterModule(e.target.value)}
                className="flex h-9 rounded-md border border-input bg-background px-3 py-1 text-sm"
              >
                <option value="all">Todos los módulos</option>
                {modules.map(m => (
                  <option key={m.id} value={m.id}>{m.name}</option>
                ))}
              </select>
              <select
                value={filterDifficulty}
                onChange={(e) => setFilterDifficulty(e.target.value)}
                className="flex h-9 rounded-md border border-input bg-background px-3 py-1 text-sm"
              >
                <option value="all">Todas dificultades</option>
                <option value="EASY">Fácil</option>
                <option value="MEDIUM">Medio</option>
                <option value="HARD">Difícil</option>
              </select>
              <Button
                variant={filterPublished === 'all' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('all')}
              >
                Todos
              </Button>
              <Button
                variant={filterPublished === 'published' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('published')}
              >
                Publicados
              </Button>
              <Button
                variant={filterPublished === 'unpublished' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setFilterPublished('unpublished')}
              >
                No publicados
              </Button>
              <Button variant="ghost" size="icon" onClick={() => void fetchData()}>
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5" />
            Ejercicios ({filteredExercises.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {filteredExercises.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Módulo</TableHead>
                  <TableHead>Tipo</TableHead>
                  <TableHead>Dificultad</TableHead>
                  <TableHead>Enunciado</TableHead>
                  <TableHead>Pts</TableHead>
                  <TableHead>IA</TableHead>
                  <TableHead>Estado</TableHead>
                  <TableHead className="text-right">Acciones</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredExercises.map((exercise) => (
                  <TableRow key={exercise.id}>
                    <TableCell className="font-medium">{exercise.order}</TableCell>
                    <TableCell className="text-muted-foreground">
                      {exercise.module?.name ?? 'Sin módulo'}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{getTypeLabel(exercise.type)}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className={getDifficultyColor(exercise.difficulty)}>
                        {exercise.difficulty}
                      </Badge>
                    </TableCell>
                    <TableCell className="max-w-xs truncate">
                      {exercise.statement.substring(0, 50)}...
                    </TableCell>
                    <TableCell>{exercise.points}</TableCell>
                    <TableCell>
                      {exercise.isAIGenerated && <Sparkles className="h-4 w-4 text-amber-500" />}
                    </TableCell>
                    <TableCell>
                      <Badge variant={exercise.isPublished ? 'default' : 'secondary'}>
                        {exercise.isPublished ? 'Publicado' : 'No publicado'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button variant="ghost" size="icon" onClick={() => handleTogglePublish(exercise.id)}>
                          {exercise.isPublished ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                        </Button>
                        <Button variant="ghost" size="icon" disabled>
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" disabled>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <EmptyState
              icon={<FileText className="h-12 w-12" />}
              title="No hay ejercicios"
              description="No se encontraron ejercicios con los filtros seleccionados."
              action={{
                label: 'Generar con IA',
                onClick: () => router.push('/admin/generate'),
              }}
            />
          )}
        </CardContent>
      </Card>

      <Card className="border-amber-500/20 bg-amber-500/5">
        <CardContent className="p-4">
          <p className="text-sm text-amber-600">
            <strong>Nota:</strong> Las acciones CRUD de ejercicios requieren endpoints en el backend que aún no están implementados.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
