'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  Sparkles,
  RefreshCw,
  CheckCircle,
  AlertCircle,
  Clock,
  Zap,
} from 'lucide-react';
import { api, apiEndpoints } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';
import { Skeleton } from '@/components/ui/skeleton';
import type { ModuleType, ExerciseType, ExerciseDifficulty } from '@/types';

interface GeneratedExercise {
  id: string;
  statement: string;
  correctAnswer: string;
  solutionSteps: { step: number; description: string; formula?: string }[];
  difficulty: ExerciseDifficulty;
  type: ExerciseType;
  points: number;
  isAIGenerated: boolean;
}

interface Module {
  id: string;
  name: string;
  type: ModuleType;
}

const TOPIC_OPTIONS = [
  { value: 'VECTORES', label: 'Vectores' },
  { value: 'MATRICES', label: 'Matrices' },
  { value: 'SISTEMAS', label: 'Sistemas de Ecuaciones' },
  { value: 'ESPACIOS_VECTORIALES', label: 'Espacios Vectoriales' },
  { value: 'PROGRAMACION_LINEAL', label: 'Programación Lineal' },
];

const MODULE_TYPE_OPTIONS = [
  { value: 'FUNDAMENTOS', label: 'Fundamentos' },
  { value: 'SISTEMAS', label: 'Sistemas' },
  { value: 'APLICACIONES', label: 'Aplicaciones' },
];

const EXERCISE_TYPE_OPTIONS = [
  { value: 'MULTIPLE_CHOICE', label: 'Opción Múltiple' },
  { value: 'OPEN_ENDED', label: 'Respuesta Abierta' },
  { value: 'TRUE_FALSE', label: 'Verdadero/Falso' },
  { value: 'CALCULATION', label: 'Calculación' },
];

const DIFFICULTY_OPTIONS = [
  { value: 'EASY', label: 'Fácil (10 pts)' },
  { value: 'MEDIUM', label: 'Medio (20 pts)' },
  { value: 'HARD', label: 'Difícil (30 pts)' },
];

export default function AdminGeneratePage() {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [modules, setModules] = useState<Module[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [progress, setProgress] = useState(0);
  const [progressMessage, setProgressMessage] = useState('');
  const [generatedExercise, setGeneratedExercise] = useState<GeneratedExercise | null>(null);

  const [selectedModule, setSelectedModule] = useState<string>('');
  const [selectedTopic, setSelectedTopic] = useState<string>('VECTORES');
  const [selectedModuleType, setSelectedModuleType] = useState<string>('FUNDAMENTOS');
  const [selectedExerciseType, setSelectedExerciseType] = useState<string>('CALCULATION');
  const [selectedDifficulty, setSelectedDifficulty] = useState<string>('MEDIUM');
  const [context, setContext] = useState<string>('');
  const [publishImmediately, setPublishImmediately] = useState(false);

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

  const fetchModules = async () => {
    try {
      setIsLoading(true);
      const data: { data?: Module[] } | Module[] = await api.get<{ data: Module[] }>(apiEndpoints.modules.list);
      const modulesList: Module[] = Array.isArray(data) ? data : (data?.data ?? []);
      setModules(modulesList);
      if (modulesList.length > 0 && modulesList[0]?.id) {
        setSelectedModule(modulesList[0].id);
      }
    } catch (error) {
      toast({
        title: 'Error al cargar módulos',
        description: 'No se pudo cargar los módulos',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGenerate = async () => {
    if (!selectedModule) {
      toast({
        title: 'Selecciona un módulo',
        description: 'Debes seleccionar un módulo para asociar el ejercicio.',
        variant: 'destructive',
      });
      return;
    }

    setIsGenerating(true);
    setProgress(0);
    setProgressMessage('Iniciando...');
    setGeneratedExercise(null);

    try {
      setProgressMessage('Generando ejercicio...');
      setProgress(30);

      const result = await api.post<{
        success: boolean;
        data: {
          exerciseIds?: string[];
          exercisesGenerated: number;
          metadata?: { generationTimeMs?: number };
        };
      }>(apiEndpoints.admin.generateExercise, {
        topic: selectedTopic,
        moduleType: selectedModuleType,
        exerciseType: selectedExerciseType,
        difficulty: selectedDifficulty,
        moduleId: selectedModule,
        isPublished: publishImmediately,
        context: context || undefined,
      });

      setProgress(80);
      
      if (result.data?.exerciseIds && result.data.exerciseIds.length > 0) {
        const firstId = result.data.exerciseIds[0];
        if (firstId) {
          await fetchGeneratedExercise(firstId);
        }
      }

      setProgress(100);
      setProgressMessage('Completado');

      toast({
        title: 'Ejercicio generado',
        description: `Generado exitosamente`,
      });
    } catch (error) {
      toast({
        title: 'Error al generar',
        description: error instanceof Error ? error.message : 'Error desconocido',
        variant: 'destructive',
      });
    } finally {
      setIsGenerating(false);
    }
  };

  const fetchGeneratedExercise = async (exerciseId: string) => {
    try {
      const exercise = await api.get<GeneratedExercise>(
        apiEndpoints.exercises.detail(exerciseId) + '?hideSolution=false'
      );
      setGeneratedExercise(exercise);
    } catch {
      setGeneratedExercise({
        id: exerciseId,
        statement: 'Ejercicio generado exitosamente (ver detalles en la lista de ejercicios)',
        correctAnswer: '',
        solutionSteps: [],
        difficulty: selectedDifficulty as ExerciseDifficulty,
        type: selectedExerciseType as ExerciseType,
        points: selectedDifficulty === 'EASY' ? 10 : selectedDifficulty === 'MEDIUM' ? 20 : 30,
        isAIGenerated: true,
      });
    }
  };

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

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-4 w-64" />
        <div className="grid gap-6 lg:grid-cols-2">
          <Skeleton className="h-96 w-full" />
          <Skeleton className="h-96 w-full" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Generación con IA</h1>
        <p className="text-muted-foreground">Genera ejercicios automáticamente usando inteligencia artificial</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Zap className="h-5 w-5" />
              Configuración
            </CardTitle>
            <CardDescription>Selecciona los parámetros para la generación</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <label htmlFor="module-select" className="text-sm font-medium">Módulo</label>
              <select
                id="module-select"
                value={selectedModule}
                onChange={(e) => setSelectedModule(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                <option value="">Seleccionar módulo...</option>
                {modules.map(m => (
                  <option key={m.id} value={m.id}>{m.name}</option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label htmlFor="topic-select" className="text-sm font-medium">Tema</label>
              <select
                id="topic-select"
                value={selectedTopic}
                onChange={(e) => setSelectedTopic(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                {TOPIC_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label htmlFor="module-type-select" className="text-sm font-medium">Tipo de Módulo</label>
              <select
                id="module-type-select"
                value={selectedModuleType}
                onChange={(e) => setSelectedModuleType(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                {MODULE_TYPE_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label htmlFor="exercise-type-select" className="text-sm font-medium">Tipo de Ejercicio</label>
              <select
                id="exercise-type-select"
                value={selectedExerciseType}
                onChange={(e) => setSelectedExerciseType(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                {EXERCISE_TYPE_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label htmlFor="difficulty-select" className="text-sm font-medium">Dificultad</label>
              <select
                id="difficulty-select"
                value={selectedDifficulty}
                onChange={(e) => setSelectedDifficulty(e.target.value)}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                {DIFFICULTY_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label htmlFor="context-textarea" className="text-sm font-medium">Contexto adicional (opcional)</label>
              <textarea
                id="context-textarea"
                value={context}
                onChange={(e) => setContext(e.target.value)}
                placeholder="Ej: Debe incluir fracciones, usar notación LaTeX..."
                className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              />
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="publish"
                checked={publishImmediately}
                onChange={(e) => setPublishImmediately(e.target.checked)}
                className="h-4 w-4"
              />
              <label htmlFor="publish" className="text-sm">Publicar inmediatamente</label>
            </div>

            {isGenerating && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 animate-spin" />
                  <span className="text-sm">{progressMessage}</span>
                </div>
                <Progress value={progress} />
              </div>
            )}

            <Button
              onClick={() => void handleGenerate()}
              disabled={isGenerating || !selectedModule}
              className="w-full"
            >
              {isGenerating ? (
                <>
                  <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                  Generando...
                </>
              ) : (
                <>
                  <Sparkles className="mr-2 h-4 w-4" />
                  Generar Ejercicio
                </>
              )}
            </Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              {generatedExercise ? <CheckCircle className="h-5 w-5 text-green-500" /> : <AlertCircle className="h-5 w-5 text-muted-foreground" />}
              Preview
            </CardTitle>
            <CardDescription>Ejercicio generado</CardDescription>
          </CardHeader>
          <CardContent>
            {generatedExercise ? (
              <div className="space-y-4">
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className={getDifficultyColor(generatedExercise.difficulty)}>
                    {generatedExercise.difficulty}
                  </Badge>
                  <Badge variant="outline">{generatedExercise.points} pts</Badge>
                  <Badge className="bg-amber-500/10 text-amber-600">
                    <Sparkles className="mr-1 h-3 w-3" />IA
                  </Badge>
                </div>

                <div className="space-y-2">
                  <label htmlFor="exercise-statement" className="text-sm font-medium">Enunciado</label>
                  <div id="exercise-statement" className="rounded-md border p-4 bg-muted/50">
                    <p className="text-sm">{generatedExercise.statement}</p>
                  </div>
                </div>

                <div className="space-y-2">
                  <label htmlFor="exercise-answer" className="text-sm font-medium">Respuesta Correcta</label>
                  <div id="exercise-answer" className="rounded-md border p-3 bg-green-500/10">
                    <p className="text-sm font-medium text-green-600">{generatedExercise.correctAnswer ?? 'Ver ejercicio guardado'}</p>
                  </div>
                </div>

                <div className="flex gap-2">
                  <Button onClick={() => void handleGenerate()} variant="outline" disabled={isGenerating}>
                    <RefreshCw className="mr-2 h-4 w-4" />
                    Regenerar
                  </Button>
                </div>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <Sparkles className="h-12 w-12 text-muted-foreground mb-4" />
                <p className="text-muted-foreground">
                  Configura los parámetros y presiona &quot;Generar&quot; para crear un ejercicio con IA
                </p>
                <p className="text-xs text-muted-foreground mt-2">La generación puede tardar 10-60 segundos</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      <Card className="border-blue-500/20 bg-blue-500/5">
        <CardContent className="p-4">
          <div className="flex items-start gap-3">
            <Zap className="h-5 w-5 text-blue-500" />
            <div>
              <p className="text-sm font-medium text-blue-600">Generación con DashScope AI</p>
              <p className="text-xs text-blue-500 mt-1">
                El sistema usa el modelo Qwen de DashScope para generar ejercicios matemáticos con pasos de solución.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
