"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import {
  Check,
  MessageSquarePlus,
  X,
  ChevronLeft,
  ChevronRight,
  Save,
  User,
  AlertCircle,
  Clock
} from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { Separator } from "@/shared/components/ui/separator"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/components/ui/tooltip"
import { gradeHomeworkSubmissionAction } from "../actions"
import { formatDate } from "@/shared/lib/utils"
import { QuestionRenderer } from "./question-renderer"
import { AiGradingAssist } from "@/modules/ai/components/ai-grading-assist"
import {
  applyAutoGrades,
  extractAnswerValue,
  extractQuestionText,
  formatStudentAnswer,
  getCorrectnessState,
  getOptions,
  getTextCorrectAnswers,
  isAutoGradable,
} from "../lib/question-content-utils"
import type { HomeworkSubmissionAnswerDetails } from "../types"

type HomeworkGradingViewProps = {
  submissionId: string
  studentName: string
  assignmentTitle: string
  submittedAt: string | null
  status: string
  totalScore: number | null
  answers: HomeworkSubmissionAnswerDetails[]
  prevSubmissionId?: string | null
  nextSubmissionId?: string | null
}

export function HomeworkGradingView({
  submissionId,
  answers: initialAnswers,
  prevSubmissionId,
  nextSubmissionId,
  studentName,
  assignmentTitle,
  submittedAt,
}: HomeworkGradingViewProps) {
  const router = useRouter()
  const t = useTranslations("examHomework")
  const [answers, setAnswers] = useState(() => applyAutoGrades(initialAnswers))
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  // Initialize feedback visibility for answers that already have feedback
  const [showFeedbackByAnswerId, setShowFeedbackByAnswerId] = useState<Record<string, boolean>>(() => {
    const initialVisibility: Record<string, boolean> = {}
    if (initialAnswers) {
      initialAnswers.forEach(a => {
        if (a.feedback && a.feedback.trim().length > 0) {
          initialVisibility[a.id] = true
        }
      })
    }
    return initialVisibility
  })

  const handleManualScoreChange = (id: string, val: string) => {
    const parsed = val === "" ? 0 : Number(val)
    // Clamp score between 0 and maxScore? Or allow extra credit? 
    // Usually maxScore is the limit, but let's just ensure it's a number.
    // Ideally we should clamp it to [0, maxScore] to avoid errors, but sometimes teachers want to give 0 for invalid input.
    const targetAnswer = answers.find(a => a.id === id)
    const max = targetAnswer?.maxScore ?? 100
    
    let nextScore = Number.isFinite(parsed) ? parsed : 0
    if (nextScore > max) nextScore = max
    if (nextScore < 0) nextScore = 0

    setAnswers((prev) => prev.map((a) => (a.id === id ? { ...a, score: nextScore } : a)))
  }

  const handleMarkCorrect = (id: string) => {
    setAnswers((prev) => prev.map((a) => (a.id === id ? { ...a, score: a.maxScore } : a)))
  }

  const handleMarkIncorrect = (id: string) => {
    setAnswers((prev) => prev.map((a) => (a.id === id ? { ...a, score: 0 } : a)))
  }

  const handleFeedbackChange = (id: string, val: string) => {
    setAnswers((prev) => prev.map((a) => (a.id === id ? { ...a, feedback: val } : a)))
  }

  const currentTotal = answers.reduce((sum, a) => sum + (a.score || 0), 0)
  const maxTotal = answers.reduce((sum, a) => sum + a.maxScore, 0)
  const progressPercent = maxTotal > 0 ? (currentTotal / maxTotal) * 100 : 0
  
  const correctCount = answers.reduce((sum, a) => sum + (a.score === a.maxScore ? 1 : 0), 0)
  const incorrectCount = answers.reduce((sum, a) => sum + (a.score === 0 ? 1 : 0), 0)
  const partialCount = answers.reduce((sum, a) => sum + (a.score !== null && a.score > 0 && a.score < a.maxScore ? 1 : 0), 0)

  const handleSubmit = async () => {
    setIsSubmitting(true)
    const payload = answers.map((a) => {
      const feedback =
        typeof a.feedback === "string" && a.feedback.trim().length > 0 ? a.feedback.trim() : undefined
      return { id: a.id, score: a.score || 0, feedback }
    })

    const formData = new FormData()
    formData.set("submissionId", submissionId)
    formData.set("answersJson", JSON.stringify(payload))

    try {
      const result = await gradeHomeworkSubmissionAction(null, formData)

      if (result.success) {
        toast.success(t("homework.grade.gradesSaved"))
        // Optionally redirect or stay
        router.refresh()
      } else {
        toast.error(result.message || t("homework.grade.gradesSaveFailed"))
      }
    } catch {
      toast.error(t("homework.grade.gradesSaveFailed"))
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleScrollToQuestion = (id: string) => {
    const el = document.getElementById(`question-card-${id}`)
    if (el) {
      el.scrollIntoView({ behavior: "smooth", block: "start" })
    }
  }

  return (
    <div className="grid h-[calc(100vh-8rem)] grid-cols-1 gap-6 lg:grid-cols-12">
      {/* Main Content: Questions List */}
      <div className="lg:col-span-9 h-full overflow-hidden flex flex-col rounded-md border bg-muted/10">
        <ScrollArea className="flex-1 p-4 lg:p-8">
          <div className="mx-auto max-w-4xl space-y-8 pb-20">
            {answers.map((ans, index) => {
              const correctness = getCorrectnessState({ score: ans.score, maxScore: ans.maxScore })
              const borderClass =
                correctness === "correct"
                  ? "border-l-4 border-l-emerald-500"
                  : correctness === "incorrect"
                  ? "border-l-4 border-l-red-500"
                  : "border-l-4 border-l-muted"
              return (
                <Card id={`question-card-${ans.id}`} key={ans.id} className={`overflow-hidden transition-all ${borderClass}`}>
                  <CardHeader className="bg-card pb-4">
                    <QuestionRenderer
                      questionId={ans.id}
                      questionType={ans.questionType}
                      questionContent={ans.questionContent}
                      maxScore={ans.maxScore}
                      index={index}
                      mode="grade"
                      value={extractAnswerValue(ans.studentAnswer)}
                      showCorrectAnswer={true}
                      headerExtra={
                        <div className="flex flex-col items-end gap-1">
                          <Badge variant="outline" className="whitespace-nowrap">
                            <span className="sr-only">{t("homework.grade.scoreLabel")}: </span>
                            {ans.score ?? 0} / {ans.maxScore} pts
                          </Badge>
                          {isAutoGradable({ questionType: ans.questionType, questionContent: ans.questionContent }) && (
                            <Badge variant="secondary" className="text-[10px] h-5">{t("homework.grade.autoGraded")}</Badge>
                          )}
                        </div>
                      }
                    />
                  </CardHeader>

                  <Separator />

                  <CardContent className="bg-card/50 p-6 space-y-6">
                    {/* Student Answer Display */}
                    <div className="space-y-3">
                      <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
                        <User className="h-3 w-3" /> {t("homework.grade.studentAnswer")}
                      </Label>

                      <div className="rounded-md border bg-background p-4 shadow-sm">
                        {(ans.questionType === "single_choice" || ans.questionType === "multiple_choice") &&
                        Array.isArray(ans.questionContent?.options) ? (
                          <div className="space-y-2">
                            {getOptions(ans.questionContent).map((opt) => {
                              const answerValue = extractAnswerValue(ans.studentAnswer)
                              const isSelected = Array.isArray(answerValue)
                                ? answerValue.filter((x): x is string => typeof x === "string").includes(opt.id)
                                : typeof answerValue === "string" && answerValue === opt.id

                              const isCorrect = opt.isCorrect === true

                              let containerClass = "border-transparent hover:bg-muted/50"
                              let indicatorClass = "border-muted-foreground/30 text-muted-foreground"

                              if (isSelected) {
                                if (isCorrect) {
                                  containerClass = "border-emerald-500 bg-emerald-50/50 dark:bg-emerald-950/20"
                                  indicatorClass = "border-emerald-500 bg-emerald-500 text-white"
                                } else {
                                  containerClass = "border-red-500 bg-red-50/50 dark:bg-red-950/20"
                                  indicatorClass = "border-red-500 bg-red-500 text-white"
                                }
                              } else if (isCorrect) {
                                  containerClass = "border-emerald-200 bg-emerald-50/30 dark:border-emerald-800 dark:bg-emerald-950/10"
                                  indicatorClass = "border-emerald-500 text-emerald-600 dark:text-emerald-400"
                              }

                              return (
                                <div
                                  key={opt.id}
                                  className={`flex items-center gap-3 rounded-md border p-3 text-sm transition-colors ${containerClass}`}
                                >
                                  <div className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-medium ${indicatorClass}`}>
                                    {opt.id}
                                  </div>
                                  <span className="flex-1">{opt.text}</span>
                                  <span className="sr-only">
                                    {isCorrect ? t("homework.grade.correct") : ""} {isSelected && !isCorrect ? t("homework.grade.incorrect") : ""}
                                  </span>
                                  {isCorrect && <Check className="h-4 w-4 text-emerald-600" aria-hidden="true" />}
                                  {isSelected && !isCorrect && <X className="h-4 w-4 text-red-600" aria-hidden="true" />}
                                </div>
                              )
                            })}
                          </div>
                        ) : (
                          <p className="whitespace-pre-wrap text-sm leading-relaxed">
                            {formatStudentAnswer(ans.studentAnswer)}
                          </p>
                        )}
                      </div>
                    </div>

                    {/* Reference Answer (for text/non-choice questions) */}
                    {ans.questionType === "text" && (
                      <div className="space-y-2">
                         <Label className="text-xs font-semibold text-emerald-600/90 uppercase tracking-wider flex items-center gap-2">
                           <Check className="h-3 w-3" /> {t("homework.grade.referenceAnswer")}
                         </Label>
                         <div className="rounded-md border border-emerald-200 bg-emerald-50/30 p-4 text-sm text-muted-foreground dark:border-emerald-900/50 dark:bg-emerald-950/10">
                           {getTextCorrectAnswers(ans.questionContent).join(" / ") || t("homework.grade.noReferenceAnswer")}
                         </div>
                      </div>
                    )}
                  </CardContent>

                  <CardFooter className="bg-muted/30 p-4 border-t flex flex-col gap-4">
                     <div className="flex flex-wrap items-center justify-between w-full gap-4">
                        {/* Grading Controls */}
                        <div className="flex flex-wrap items-center gap-4">
                          <div className="flex items-center gap-2">
                            <Button
                              variant={correctness === "correct" ? "default" : "outline"}
                              size="sm"
                              aria-pressed={correctness === "correct"}
                              className={correctness === "correct" ? "bg-emerald-600 hover:bg-emerald-700 text-white border-transparent" : "text-muted-foreground hover:text-emerald-600 hover:border-emerald-200"}
                              onClick={() => handleMarkCorrect(ans.id)}
                            >
                              <Check className="mr-1 h-4 w-4" /> {t("homework.grade.correctButton")}
                            </Button>
                            <Button
                              variant={correctness === "incorrect" ? "destructive" : "outline"}
                              size="sm"
                              aria-pressed={correctness === "incorrect"}
                              className={correctness === "incorrect" ? "" : "text-muted-foreground hover:text-red-600 hover:border-red-200"}
                              onClick={() => handleMarkIncorrect(ans.id)}
                            >
                              <X className="mr-1 h-4 w-4" /> {t("homework.grade.incorrectButton")}
                            </Button>
                          </div>

                          <Separator orientation="vertical" className="h-6 hidden sm:block" />

                          <div className="flex items-center gap-2">
                            <Label htmlFor={`score-${ans.id}`} className="whitespace-nowrap text-sm font-medium">{t("homework.grade.scoreLabel")}:</Label>
                            <Input
                              id={`score-${ans.id}`}
                              type="number"
                              min={0}
                              max={ans.maxScore}
                              className="w-20 h-8"
                              value={ans.score ?? ""}
                              onChange={(e) => handleManualScoreChange(ans.id, e.target.value)}
                            />
                            <span className="text-sm text-muted-foreground">/ {ans.maxScore}</span>
                          </div>
                        </div>

                        {/* Feedback Toggle */}
                        <Button
                          variant="ghost"
                          size="sm"
                          aria-pressed={Boolean(showFeedbackByAnswerId[ans.id])}
                          className={showFeedbackByAnswerId[ans.id] ? "bg-primary/10 text-primary" : "text-muted-foreground"}
                          onClick={() => setShowFeedbackByAnswerId(prev => ({ ...prev, [ans.id]: !prev[ans.id] }))}
                        >
                          <MessageSquarePlus className="mr-2 h-4 w-4" />
                          {showFeedbackByAnswerId[ans.id] ? t("homework.grade.hideFeedback") : t("homework.grade.addFeedback")}
                        </Button>
                     </div>

                     {/* Feedback Textarea */}
                     {showFeedbackByAnswerId[ans.id] && (
                       <div className="w-full animate-in fade-in slide-in-from-top-2 duration-200">
                         <Textarea
                           placeholder={t("homework.grade.feedbackPlaceholder", { name: studentName })}
                           value={ans.feedback ?? ""}
                           onChange={(e) => handleFeedbackChange(ans.id, e.target.value)}
                           className="min-h-[80px] bg-background"
                         />
                       </div>
                     )}

                     {/* AI Grading Assist (subjective questions only) */}
                     {!isAutoGradable({ questionType: ans.questionType, questionContent: ans.questionContent }) && (
                       <AiGradingAssist
                         questionText={extractQuestionText(ans.questionContent)}
                         questionType={ans.questionType}
                         studentAnswer={formatStudentAnswer(ans.studentAnswer)}
                         correctAnswer={getTextCorrectAnswers(ans.questionContent).join(" / ")}
                         maxScore={ans.maxScore}
                         onApplyScore={(score) => handleManualScoreChange(ans.id, String(score))}
                         onApplyFeedback={(feedback) => {
                           handleFeedbackChange(ans.id, feedback)
                           setShowFeedbackByAnswerId((prev) => ({ ...prev, [ans.id]: true }))
                         }}
                       />
                     )}
                  </CardFooter>
                </Card>
              )
            })}
          </div>
        </ScrollArea>
      </div>

      {/* Sidebar: Summary & Actions */}
      <div className="lg:col-span-3 h-full flex flex-col gap-6">
        <Card className="flex flex-col shadow-md border-t-4 border-t-primary">
          <CardHeader className="pb-2">
            <CardTitle className="text-lg">{t("homework.grade.gradingSummary")}</CardTitle>
            <CardDescription>{assignmentTitle}</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-1">
              <div className="flex items-center justify-between text-sm">
                 <span className="text-muted-foreground">{t("homework.grade.totalScore")}</span>
                 <span className="font-bold">{currentTotal} / {maxTotal}</span>
              </div>
              <div className="h-2 w-full overflow-hidden rounded-full bg-secondary">
                <div
                  className="h-full bg-primary transition-all duration-500 ease-in-out"
                  style={{ width: `${Math.min(100, Math.max(0, progressPercent))}%` }}
                />
              </div>
            </div>

            <div className="space-y-3 pt-2">
              <div className="flex items-center justify-between text-sm">
                <span className="flex items-center gap-2 text-muted-foreground">
                  <User className="h-4 w-4" /> {t("homework.grade.student")}
                </span>
                <span className="font-medium">{studentName}</span>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="flex items-center gap-2 text-muted-foreground">
                  <Clock className="h-4 w-4" /> {t("homework.grade.submitted")}
                </span>
                <span className="font-medium">
                  {submittedAt ? formatDate(submittedAt) : "N/A"}
                </span>
              </div>
            </div>

            {answers.length > 0 && (
              <div className="space-y-4 pt-2">
                 <div className="grid grid-cols-3 gap-2">
                   <div className="flex flex-col items-center justify-center rounded-md border bg-emerald-50/50 p-2 dark:bg-emerald-950/20">
                     <span className="text-2xl font-bold text-emerald-600">{correctCount}</span>
                     <span className="text-xs text-muted-foreground">{t("homework.grade.correct")}</span>
                   </div>
                   <div className="flex flex-col items-center justify-center rounded-md border bg-red-50/50 p-2 dark:bg-red-950/20">
                     <span className="text-2xl font-bold text-red-600">{incorrectCount}</span>
                     <span className="text-xs text-muted-foreground">{t("homework.grade.incorrect")}</span>
                   </div>
                   <div className="flex flex-col items-center justify-center rounded-md border bg-amber-50/50 p-2 dark:bg-amber-950/20">
                     <span className="text-2xl font-bold text-amber-600">{partialCount}</span>
                     <span className="text-xs text-muted-foreground">{t("homework.grade.partial")}</span>
                   </div>
                 </div>

                 <Separator />

                 <div>
                   <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3 block">
                     {t("homework.grade.questionStatus")}
                   </Label>
                   <div className="grid grid-cols-5 gap-2">
                     {answers.map((ans, i) => {
                      const state = getCorrectnessState({ score: ans.score, maxScore: ans.maxScore })
                       let badgeClass = "border-muted bg-muted/30 text-muted-foreground hover:bg-muted/50"
                       
                       if (state === "correct") badgeClass = "border-emerald-200 bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:border-emerald-800 dark:text-emerald-400"
                       else if (state === "incorrect") badgeClass = "border-red-200 bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:border-red-800 dark:text-red-400"
                       else if (state === "partial") badgeClass = "border-amber-200 bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:border-amber-800 dark:text-amber-400"
 
                        return (
                          <button
                            key={ans.id}
                            type="button"
                            onClick={() => handleScrollToQuestion(ans.id)}
                            className={`flex h-8 items-center justify-center rounded border text-xs font-medium transition-colors cursor-pointer hover:ring-2 hover:ring-ring hover:ring-offset-2 ${badgeClass}`}
                            title={`Q${i + 1}: ${state}`}
                          >
                            {i + 1}
                          </button>
                        )
                      })}
                   </div>
                 </div>
              </div>
            )}
          </CardContent>
          <CardFooter className="flex flex-col gap-3 pt-2">
             <Button 
               className="w-full" 
               size="lg" 
               onClick={handleSubmit} 
               disabled={isSubmitting}
             >
               {isSubmitting ? (
                 <>{t("homework.grade.saving")}</>
               ) : (
                 <>
                   <Save className="mr-2 h-4 w-4" /> {t("homework.grade.submitGrades")}
                 </>
               )}
            </Button>

            <div className="flex w-full items-center justify-between gap-2 pt-2">
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      disabled={!prevSubmissionId}
                      onClick={() => prevSubmissionId && router.push(`/teacher/homework/submissions/${prevSubmissionId}`)}
                    >
                      <ChevronLeft className="mr-1 h-4 w-4" /> {t("homework.grade.prev")}
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>{t("homework.grade.previousStudent")}</TooltipContent>
                </Tooltip>

                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      disabled={!nextSubmissionId}
                      onClick={() => nextSubmissionId && router.push(`/teacher/homework/submissions/${nextSubmissionId}`)}
                    >
                      {t("homework.grade.next")} <ChevronRight className="ml-1 h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>{t("homework.grade.nextStudent")}</TooltipContent>
                </Tooltip>
             </div>
          </CardFooter>
        </Card>
        
        <div className="rounded-md bg-blue-50 p-4 text-sm text-blue-800 dark:bg-blue-950/30 dark:text-blue-300 border border-blue-200 dark:border-blue-900">
           <div className="flex items-start gap-2">
             <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
             <p>
               {t("homework.grade.gradesAutoSaveNote")}
             </p>
           </div>
        </div>
      </div>
    </div>
  )
}

