"use client"

import { useState } from "react"
import { useFormStatus } from "react-dom"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
import { Textarea } from "@/shared/components/ui/textarea"

import { createGradeRecordAction } from "../actions"

type Option = { id: string; name: string }
type GradeType = "exam" | "quiz" | "homework" | "other"
type Semester = "1" | "2"

function isGradeType(v: string): v is GradeType {
  return v === "exam" || v === "quiz" || v === "homework" || v === "other"
}

function isSemester(v: string): v is Semester {
  return v === "1" || v === "2"
}

function SubmitButton() {
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? "Saving..." : "Save Record"}
    </Button>
  )
}

export function GradeRecordForm({
  classes,
  subjects,
  students,
  defaultClassId,
  defaultSubjectId,
}: {
  classes: Option[]
  subjects: Option[]
  students: Option[]
  defaultClassId?: string
  defaultSubjectId?: string
}) {
  const router = useRouter()
  const [classId, setClassId] = useState(defaultClassId ?? classes[0]?.id ?? "")
  const [subjectId, setSubjectId] = useState(defaultSubjectId ?? subjects[0]?.id ?? "")
  const [studentId, setStudentId] = useState(students[0]?.id ?? "")
  const [type, setType] = useState<GradeType>("exam")
  const [semester, setSemester] = useState<Semester>("1")

  const handleSubmit = async (formData: FormData) => {
    if (!classId || !subjectId || !studentId) {
      toast.error("Please select class, subject and student")
      return
    }
    formData.set("classId", classId)
    formData.set("subjectId", subjectId)
    formData.set("studentId", studentId)
    formData.set("type", type)
    formData.set("semester", semester)

    const result = await createGradeRecordAction(null, formData)
    if (result.success) {
      toast.success(result.message)
      router.push("/teacher/grades")
      router.refresh()
    } else {
      toast.error(result.message || "Failed to create")
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Record Grade</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label>Class</Label>
              <Select value={classId} onValueChange={setClassId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a class" />
                </SelectTrigger>
                <SelectContent>
                  {classes.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label>Subject</Label>
              <Select value={subjectId} onValueChange={setSubjectId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a subject" />
                </SelectTrigger>
                <SelectContent>
                  {subjects.map((s) => (
                    <SelectItem key={s.id} value={s.id}>
                      {s.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2 md:col-span-2">
              <Label>Student</Label>
              <Select value={studentId} onValueChange={setStudentId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a student" />
                </SelectTrigger>
                <SelectContent>
                  {students.map((s) => (
                    <SelectItem key={s.id} value={s.id}>
                      {s.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2 md:col-span-2">
              <Label htmlFor="title">Title</Label>
              <Input id="title" name="title" placeholder="e.g. Mid-term Exam" required />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="score">Score</Label>
              <Input id="score" name="score" type="number" step="0.01" min="0" required />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="fullScore">Full Score</Label>
              <Input id="fullScore" name="fullScore" type="number" step="0.01" min="1" defaultValue="100" />
            </div>

            <div className="grid gap-2">
              <Label>Type</Label>
              <Select value={type} onValueChange={(v) => { if (isGradeType(v)) setType(v) }}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="exam">Exam</SelectItem>
                  <SelectItem value="quiz">Quiz</SelectItem>
                  <SelectItem value="homework">Homework</SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label>Semester</Label>
              <Select value={semester} onValueChange={(v) => { if (isSemester(v)) setSemester(v) }}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Semester 1</SelectItem>
                  <SelectItem value="2">Semester 2</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2 md:col-span-2">
              <Label htmlFor="remark">Remark (optional)</Label>
              <Textarea id="remark" name="remark" placeholder="Notes about this grade..." />
            </div>
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button type="button" variant="outline" onClick={() => router.back()}>
              Cancel
            </Button>
            <SubmitButton />
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
