"use client"

import React, { useState, useEffect, useCallback } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { MoonUIFormWizardPro, WizardStep } from "../form-wizard"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card"
import { Button } from "../ui/button"
import { RadioGroup, RadioGroupItem } from "../ui/radio-group"
import { Checkbox } from "../ui/checkbox"
import { Label } from "../ui/label"
import { Progress } from "../ui/progress"
import { Slider } from "../ui/slider"
import { Textarea } from "../ui/textarea"
import { Badge } from "../ui/badge"
import { cn } from "../../lib/utils"
import { Clock, Trophy, Target, ChevronRight, RotateCcw, Download, Share2 } from "lucide-react"

export type QuestionType = 'single-choice' | 'multiple-choice' | 'text' | 'rating' | 'true-false' | 'matching'

export interface QuizAnswer {
  value: string | string[] | number | boolean
  label?: string
  isCorrect?: boolean
  points?: number
}

export interface QuizQuestion {
  id: string
  type: QuestionType
  question: string
  description?: string
  image?: string
  options?: QuizAnswer[]
  correctAnswer?: string | string[] | number | boolean
  points?: number
  timeLimit?: number // in seconds
  required?: boolean
  explanation?: string
  hint?: string
  tags?: string[]
}

export interface QuizResult {
  questionId: string
  answer: any
  isCorrect?: boolean
  points: number
  timeSpent: number
}

export interface QuizFormProps {
  title: string
  description?: string
  questions: QuizQuestion[]
  onComplete?: (results: QuizResult[], score: number, totalScore: number) => void | Promise<void>
  showTimer?: boolean
  totalTimeLimit?: number // in seconds
  showProgress?: boolean
  showQuestionNumbers?: boolean
  allowReview?: boolean
  allowSkip?: boolean
  shuffleQuestions?: boolean
  shuffleOptions?: boolean
  passingScore?: number // percentage
  instantFeedback?: boolean
  showHints?: boolean
  className?: string
}

function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  return shuffled
}

export const MoonUIQuizFormPro: React.FC<QuizFormProps> = ({
  title,
  description,
  questions: initialQuestions,
  onComplete,
  showTimer = true,
  totalTimeLimit,
  showProgress = true,
  showQuestionNumbers = true,
  allowReview = true,
  allowSkip = true,
  shuffleQuestions = false,
  shuffleOptions = false,
  passingScore = 70,
  instantFeedback = false,
  showHints = false,
  className
}) => {
  const [questions] = useState(() => 
    shuffleQuestions ? shuffleArray(initialQuestions) : initialQuestions
  )
  const [answers, setAnswers] = useState<Record<string, any>>({})
  const [results, setResults] = useState<QuizResult[]>([])
  const [timeRemaining, setTimeRemaining] = useState(totalTimeLimit || 0)
  const [questionStartTime, setQuestionStartTime] = useState<Record<string, number>>({})
  const [showResults, setShowResults] = useState(false)
  const [currentQuestionTime, setCurrentQuestionTime] = useState(0)

  // Timer effect
  useEffect(() => {
    if (!showTimer || !totalTimeLimit || showResults) return

    const interval = setInterval(() => {
      setTimeRemaining(prev => {
        if (prev <= 1) {
          handleQuizComplete()
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(interval)
  }, [showTimer, totalTimeLimit, showResults])

  // Current question timer
  useEffect(() => {
    if (!showTimer || showResults) return

    const interval = setInterval(() => {
      setCurrentQuestionTime(prev => prev + 1)
    }, 1000)

    return () => clearInterval(interval)
  }, [showTimer, showResults])

  const calculateScore = useCallback(() => {
    let score = 0
    let totalScore = 0

    const quizResults: QuizResult[] = questions.map(question => {
      const answer = answers[question.id]
      const points = question.points || 1
      totalScore += points

      let isCorrect = false
      if (answer !== undefined && answer !== null && answer !== '') {
        if (question.type === 'single-choice' || question.type === 'true-false') {
          isCorrect = answer === question.correctAnswer
        } else if (question.type === 'multiple-choice') {
          const userAnswers = Array.isArray(answer) ? answer : []
          const correctAnswers = Array.isArray(question.correctAnswer) ? question.correctAnswer : []
          isCorrect = userAnswers.length === correctAnswers.length &&
            userAnswers.every(a => correctAnswers.includes(a))
        }
      }

      const earnedPoints = isCorrect ? points : 0
      score += earnedPoints

      return {
        questionId: question.id,
        answer,
        isCorrect,
        points: earnedPoints,
        timeSpent: questionStartTime[question.id] || 0
      }
    })

    return { results: quizResults, score, totalScore }
  }, [questions, answers, questionStartTime])

  const handleQuizComplete = async () => {
    const { results, score, totalScore } = calculateScore()
    setResults(results)
    setShowResults(true)
    
    if (onComplete) {
      await onComplete(results, score, totalScore)
    }
  }

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  const wizardSteps: WizardStep[] = questions.map((question, index) => ({
    id: question.id,
    title: `Question ${index + 1}`,
    description: question.tags?.join(', '),
    content: ({ updateStepData, goToNext }) => {
      const currentAnswer = answers[question.id]
      const questionOptions = shuffleOptions && question.options 
        ? shuffleArray(question.options) 
        : question.options

      // Track time for this question
      useEffect(() => {
        if (!questionStartTime[question.id]) {
          setQuestionStartTime(prev => ({
            ...prev,
            [question.id]: currentQuestionTime
          }))
        }
      }, [])

      const handleAnswerChange = (value: any) => {
        setAnswers(prev => ({ ...prev, [question.id]: value }))
        if (instantFeedback && question.type !== 'text') {
          // Show feedback immediately
        }
      }

      return (
        <Card className="border-0 shadow-none">
          <CardHeader>
            <div className="flex items-center justify-between mb-2">
              {showQuestionNumbers && (
                <Badge variant="secondary">
                  Question {index + 1} of {questions.length}
                </Badge>
              )}
              {question.points && question.points > 1 && (
                <Badge variant="outline">
                  {question.points} points
                </Badge>
              )}
            </div>
            <CardTitle className="text-xl">{question.question}</CardTitle>
            {question.description && (
              <CardDescription>{question.description}</CardDescription>
            )}
          </CardHeader>
          <CardContent className="space-y-4">
            {question.image && (
              <img 
                src={question.image} 
                alt="Question illustration" 
                className="w-full rounded-lg"
              />
            )}

            {question.type === 'single-choice' && questionOptions && (
              <RadioGroup
                value={currentAnswer || ''}
                onValueChange={handleAnswerChange}
              >
                {questionOptions.map((option, optionIndex) => (
                  <motion.div
                    key={String(option.value)}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: optionIndex * 0.1 }}
                    className="flex items-center space-x-2 p-3 rounded-lg hover:bg-muted/50 transition-colors"
                  >
                    <RadioGroupItem value={String(option.value)} id={`${question.id}-${option.value}`} />
                    <Label 
                      htmlFor={`${question.id}-${option.value}`}
                      className="flex-1 cursor-pointer"
                    >
                      {option.label || option.value}
                    </Label>
                  </motion.div>
                ))}
              </RadioGroup>
            )}

            {question.type === 'multiple-choice' && questionOptions && (
              <div className="space-y-2">
                {questionOptions.map((option, optionIndex) => (
                  <motion.div
                    key={String(option.value)}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: optionIndex * 0.1 }}
                    className="flex items-center space-x-2 p-3 rounded-lg hover:bg-muted/50 transition-colors"
                  >
                    <Checkbox
                      id={`${question.id}-${option.value}`}
                      checked={(currentAnswer || []).includes(option.value)}
                      onCheckedChange={(checked) => {
                        const current = currentAnswer || []
                        if (checked) {
                          handleAnswerChange([...current, option.value])
                        } else {
                          handleAnswerChange(current.filter((v: string) => v !== option.value))
                        }
                      }}
                    />
                    <Label 
                      htmlFor={`${question.id}-${option.value}`}
                      className="flex-1 cursor-pointer"
                    >
                      {option.label || option.value}
                    </Label>
                  </motion.div>
                ))}
              </div>
            )}

            {question.type === 'true-false' && (
              <RadioGroup
                value={currentAnswer?.toString() || ''}
                onValueChange={(value) => handleAnswerChange(value === 'true')}
              >
                <div className="flex items-center space-x-2 p-3 rounded-lg hover:bg-muted/50">
                  <RadioGroupItem value="true" id={`${question.id}-true`} />
                  <Label htmlFor={`${question.id}-true`} className="flex-1 cursor-pointer">
                    True
                  </Label>
                </div>
                <div className="flex items-center space-x-2 p-3 rounded-lg hover:bg-muted/50">
                  <RadioGroupItem value="false" id={`${question.id}-false`} />
                  <Label htmlFor={`${question.id}-false`} className="flex-1 cursor-pointer">
                    False
                  </Label>
                </div>
              </RadioGroup>
            )}

            {question.type === 'text' && (
              <Textarea
                value={currentAnswer || ''}
                onChange={(e) => handleAnswerChange(e.target.value)}
                placeholder="Type your answer here..."
                className="min-h-[120px]"
              />
            )}

            {question.type === 'rating' && (
              <div className="space-y-4">
                <Slider
                  value={[currentAnswer || 5]}
                  onValueChange={([value]) => handleAnswerChange(value)}
                  max={10}
                  min={1}
                  step={1}
                  className="w-full"
                />
                <div className="text-center text-2xl font-bold">
                  {currentAnswer || 5}/10
                </div>
              </div>
            )}

            {showHints && question.hint && (
              <Alert>
                <AlertDescription>
                  <strong>Hint:</strong> {question.hint}
                </AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>
      )
    },
    validation: () => {
      if (question.required && !answers[question.id]) {
        return false
      }
      return true
    },
    isOptional: !question.required
  }))

  if (showResults) {
    const { score, totalScore } = calculateScore()
    const percentage = Math.round((score / totalScore) * 100)
    const passed = percentage >= passingScore

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        className={cn("w-full max-w-2xl mx-auto", className)}
      >
        <Card>
          <CardHeader className="text-center">
            <div className="mx-auto mb-4">
              <Trophy className={cn(
                "w-16 h-16",
                passed ? "text-yellow-500" : "text-muted-foreground"
              )} />
            </div>
            <CardTitle className="text-3xl">Quiz Complete!</CardTitle>
            <CardDescription>
              Here's how you performed
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center">
              <div className="text-5xl font-bold mb-2">
                {percentage}%
              </div>
              <Progress value={percentage} className="h-3 mb-4" />
              <div className="flex justify-between text-sm text-muted-foreground">
                <span>Score: {score}/{totalScore}</span>
                <span>
                  {passed ? (
                    <Badge variant="success">Passed</Badge>
                  ) : (
                    <Badge variant="destructive">Failed</Badge>
                  )}
                </span>
              </div>
            </div>

            {allowReview && (
              <div className="space-y-2">
                <h3 className="font-semibold">Review Answers</h3>
                {results.map((result, index) => {
                  const question = questions.find(q => q.id === result.questionId)
                  return (
                    <div key={result.questionId} className="flex items-center justify-between p-2 rounded-lg bg-muted/50">
                      <span className="text-sm">
                        {showQuestionNumbers && `Q${index + 1}: `}
                        {question?.question.substring(0, 50)}...
                      </span>
                      <Badge variant={result.isCorrect ? "success" : "destructive"}>
                        {result.points}/{question?.points || 1}
                      </Badge>
                    </div>
                  )
                })}
              </div>
            )}

            <div className="flex gap-2">
              <Button className="flex-1" onClick={() => window.location.reload()}>
                <RotateCcw className="w-4 h-4 mr-2" />
                Retake Quiz
              </Button>
              <Button variant="outline">
                <Download className="w-4 h-4 mr-2" />
                Download Results
              </Button>
              <Button variant="outline">
                <Share2 className="w-4 h-4 mr-2" />
                Share
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    )
  }

  return (
    <div className={cn("w-full", className)}>
      {showTimer && totalTimeLimit && (
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4" />
            <span className="text-sm font-medium">
              Time Remaining: {formatTime(timeRemaining)}
            </span>
          </div>
          <Progress 
            value={(timeRemaining / totalTimeLimit) * 100} 
            className="w-32 h-2"
          />
        </div>
      )}

      <MoonUIFormWizardPro
        steps={wizardSteps}
        onComplete={handleQuizComplete}
        allowStepSkip={allowSkip}
        validateOnStepChange={true}
        showProgressBar={showProgress}
        progressType="dots"
        animationType="slide"
      />
    </div>
  )
}

// Additional Alert import since it was missing
import { Alert, AlertDescription } from "../ui/alert"