import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Check, X } from "lucide-react";
import useSWR from 'swr';
import { APP_BASE_URL } from '@/utils/constants';
import { defaultFetcher } from '@/helpers/fetch.helper';
import { getEduConnectAccessToken } from '@/helpers/token.helper';
import { useToast } from '@/hooks/use-toast';

interface Course {
  id: number;
  name: string;
  description: string;
}

interface Creator {
  id: number;
  firstName: string;
  lastName: string;
  username: string;
  pfpFilename: string;
}

interface QuizAttempt {
  id: number;
  quizID: number;
  isActive: boolean;
  creationDate: string;
  quizAnswers: string[];
  quizQuestion: string;
  userAnswer: string | null;
  quizCorrectAnswer: string;
  isCorrect: boolean;
  course: Course;
  creator: Creator;
}

interface QuizGeneratorProps {
  current_page: number;
  course_uuid: string;
}

const QuizGenerator: React.FC<QuizGeneratorProps> = ({
  current_page,
  course_uuid , 
}) => {
  const { data: completedQuizzes, error: completedError } = useSWR<any>(
    `${APP_BASE_URL}/api/quiz/get/allComplete?course_uuid=${course_uuid}`,
    defaultFetcher
  );

  const { toast } = useToast()

  const { data: uncompletedQuizzes, error: uncompletedError , mutate } = useSWR<any>(
    `${APP_BASE_URL}/api/quiz/get/personalIncomplete?course_uuid=${course_uuid}`,
    defaultFetcher
  );

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(0);
  const [pendingAnswers, setPendingAnswers] = useState<Record<number, string>>({});

  const isLoading = !completedQuizzes || !uncompletedQuizzes;
  const isError = completedError || uncompletedError;

  const handleOptionSelect = (quizId: number, value: string) => {
    setPendingAnswers(prev => ({
      ...prev,
      [quizId]: value
    }));
  };

  const handleNext = () => {
    if (uncompletedQuizzes && currentQuestionIndex < uncompletedQuizzes.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
    }
  };

  const handlePrevious = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  if (isError) {
    return (
      <Card>
        <CardContent className="p-6 text-center text-red-500">
          Error loading quiz data
        </CardContent>
      </Card>
    );
  }

  if (isLoading) {
    return (
      <Card>
        <CardContent className="p-6 text-center text-gray-500">
          Loading quiz data...
        </CardContent>
      </Card>
    );
  }

  const handleGenerateQuiz = async() : Promise<void> => {
    try{
      const formData = new FormData();

      formData.append('course_uuid' , course_uuid);
      formData.append('page' , (current_page + 1)?.toString())
      const res = await fetch(APP_BASE_URL + '/api/quiz/generate' , {
        headers : {
          Authorization : `Bearer ${getEduConnectAccessToken()}`
        } , 
        body : formData,
        method : 'POST'
      });
      if(res.status == 200){
        mutate()
        toast({
          title : 'Sucessfully fetched !',
          variant : 'success'
        })
      }

    }catch(error : any){
      toast({
        title : 'Failed to fetch',
        variant : 'destructive'
      })
    }
  }

  const currentQuiz = uncompletedQuizzes?.[currentQuestionIndex];

  return (
    <div className="py-6 container mx-auto mt-8">
      <div className="grid grid-cols-3 gap-6">
        <Card className="col-span-2">
          <CardHeader>
            <CardTitle>Quiz History</CardTitle>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[400px] pr-4">
              {completedQuizzes?.data?.map((quiz, index) => (
                <div key={quiz.id} className="mb-4">
                  <div className="p-4 border rounded-lg border-gray-200">
                    <div className="flex justify-between items-center mb-2">
                      <h3 className="font-medium">{quiz.quizQuestion}</h3>
                      <span className="text-sm text-gray-500">
                        by {quiz.creator.firstName} {quiz.creator.lastName}
                      </span>
                    </div>
                    <div className="text-sm space-y-2">
                      {quiz.quizAnswers.map((answer, i) => (
                        <div 
                          key={i} 
                          className={`p-2 rounded flex justify-between items-center ${
                            answer === quiz.quizCorrectAnswer && answer === quiz.userAnswer
                              ? 'bg-green-100'
                              : answer === quiz.quizCorrectAnswer
                              ? 'bg-green-50'
                              : answer === quiz.userAnswer
                              ? 'bg-red-50'
                              : 'bg-gray-50'
                          }`}
                        >
                          <span>{answer}</span>
                          {answer === quiz.quizCorrectAnswer && (
                            <Check className="w-4 h-4 text-green-600" />
                          )}
                          {answer === quiz.userAnswer && answer !== quiz.quizCorrectAnswer && (
                            <X className="w-4 h-4 text-red-600" />
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                  {index < completedQuizzes?.length - 1 && <Separator className="my-4" />}
                </div>
              ))}
              {
                completedQuizzes?.data?.length === 0 && 'No Quiz taken yet'
              }
            </ScrollArea>
          </CardContent>
        </Card>

        <div className="space-y-6">
          {currentQuiz ? (
            <Card>
              <CardHeader>
                <CardTitle>
                  Question {currentQuestionIndex + 1} of {uncompletedQuizzes?.length}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-6">
                  <h3 className="text-lg font-medium">
                    {currentQuiz?.quizQuestion}
                  </h3>

                  <RadioGroup
                    value={pendingAnswers[currentQuiz.id] || ''}
                    onValueChange={(value) => handleOptionSelect(currentQuiz.id, value)}
                  >
                    {currentQuiz.quizAnswers.map((answer, i) => (
                      <div key={i} className="flex items-center space-x-2">
                        <RadioGroupItem value={answer} id={`option-${i}`} />
                        <Label htmlFor={`option-${i}`}>{answer}</Label>
                      </div>
                    ))}
                  </RadioGroup>

                  <div className="flex justify-between mt-6">
                    <Button 
                      onClick={handlePrevious}
                      disabled={currentQuestionIndex === 0}
                      variant="outline"
                    >
                      Previous
                    </Button>
                    <Button 
                      onClick={handleNext}
                      disabled={currentQuestionIndex === (uncompletedQuizzes?.length ?? 0) - 1}
                      className="bg-purple-700 hover:bg-purple-800"
                    >
                      Next
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardContent className="p-6 text-center text-gray-500">
                <Button className='bg-purple-700' onClick={handleGenerateQuiz}>
                  Generate Quiz Questions
                </Button>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
};

export default QuizGenerator;