"use client"

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

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"

import { createCoursePlanAction, updateCoursePlanAction } from "../actions"
import type { CoursePlanListItem, CoursePlanStatus } from "../types"

type Mode = "create" | "edit"

interface Option {
  id: string
  name: string
}

export function CoursePlanForm({
  mode,
  plan,
  classes = [],
  subjects = [],
  teachers = [],
  academicYears = [],
  backHref,
}: {
  mode: Mode
  plan?: CoursePlanListItem
  classes?: Option[]
  subjects?: Option[]
  teachers?: Option[]
  academicYears?: Option[]
  backHref?: string
}) {
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)

  const [classId, setClassId] = useState(plan?.classId ?? "")
  const [subjectId, setSubjectId] = useState(plan?.subjectId ?? "")
  const [teacherId, setTeacherId] = useState(plan?.teacherId ?? "")
  const [semester, setSemester] = useState(plan?.semester ?? "1")
  const [status, setStatus] = useState(plan?.status ?? "planning")
  const [academicYearId, setAcademicYearId] = useState(plan?.academicYearId ?? "")

  const handleSubmit = async (formData: FormData) => {
    setIsWorking(true)
    try {
      formData.set("classId", classId)
      formData.set("subjectId", subjectId)
      formData.set("teacherId", teacherId)
      formData.set("semester", semester)
      formData.set("status", status)
      if (academicYearId) formData.set("academicYearId", academicYearId)

      const res =
        mode === "create"
          ? await createCoursePlanAction(null, formData)
          : plan
            ? await updateCoursePlanAction(plan.id, null, formData)
            : null

      if (!res) {
        toast.error("Invalid form state")
        return
      }

      if (res.success) {
        toast.success(res.message)
        const redirectBase = backHref?.includes("/teacher/") ? "/teacher/course-plans" : "/admin/course-plans"
        router.push(redirectBase)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to save course plan")
      }
    } catch {
      toast.error("Failed to save course plan")
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === "create" ? "New Course Plan" : "Edit Course Plan"}
        </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>
              <input type="hidden" name="classId" value={classId} />
            </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>
              <input type="hidden" name="subjectId" value={subjectId} />
            </div>

            <div className="grid gap-2">
              <Label>Teacher</Label>
              <Select value={teacherId} onValueChange={setTeacherId}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a teacher" />
                </SelectTrigger>
                <SelectContent>
                  {teachers.map((t) => (
                    <SelectItem key={t.id} value={t.id}>
                      {t.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="teacherId" value={teacherId} />
            </div>

            <div className="grid gap-2">
              <Label>Academic Year</Label>
              <Select value={academicYearId} onValueChange={setAcademicYearId}>
                <SelectTrigger>
                  <SelectValue placeholder="Optional" />
                </SelectTrigger>
                <SelectContent>
                  {academicYears.map((y) => (
                    <SelectItem key={y.id} value={y.id}>
                      {y.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="academicYearId" value={academicYearId} />
            </div>

            <div className="grid gap-2">
              <Label>Semester</Label>
              <Select value={semester} onValueChange={(v) => setSemester(v as "1" | "2")}>
                <SelectTrigger>
                  <SelectValue placeholder="Select semester" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Semester 1</SelectItem>
                  <SelectItem value="2">Semester 2</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="semester" value={semester} />
            </div>

            <div className="grid gap-2">
              <Label>Status</Label>
              <Select value={status} onValueChange={(v) => setStatus(v as CoursePlanStatus)}>
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="planning">Planning</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                  <SelectItem value="paused">Paused</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="status" value={status} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="totalHours">Total Hours</Label>
              <Input
                id="totalHours"
                name="totalHours"
                type="number"
                min={0}
                defaultValue={plan?.totalHours ?? 0}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="weeklyHours">Weekly Hours</Label>
              <Input
                id="weeklyHours"
                name="weeklyHours"
                type="number"
                min={0}
                defaultValue={plan?.weeklyHours ?? 0}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="startDate">Start Date</Label>
              <Input
                id="startDate"
                name="startDate"
                type="date"
                defaultValue={plan?.startDate ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="endDate">End Date</Label>
              <Input
                id="endDate"
                name="endDate"
                type="date"
                defaultValue={plan?.endDate ?? ""}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="syllabus">Syllabus</Label>
            <Textarea
              id="syllabus"
              name="syllabus"
              placeholder="Teaching syllabus..."
              className="min-h-[100px]"
              defaultValue={plan?.syllabus ?? ""}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="objectives">Objectives</Label>
            <Textarea
              id="objectives"
              name="objectives"
              placeholder="Teaching objectives..."
              className="min-h-[100px]"
              defaultValue={plan?.objectives ?? ""}
            />
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button
              type="button"
              variant="outline"
              onClick={() => router.push(backHref ?? "/admin/course-plans")}
              disabled={isWorking}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? "Saving..." : mode === "create" ? "Create" : "Save"}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
