"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useTranslations } from "next-intl"
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 { createElectiveCourseAction, updateElectiveCourseAction } from "../actions"
import { isSelectionMode } from "../constants"
import type { ElectiveCourseWithDetails, ElectiveSelectionMode } from "../types"

type Mode = "create" | "edit"

interface Option {
  id: string
  name: string
}

export function ElectiveCourseForm({
  mode,
  course,
  subjects = [],
  grades = [],
  teachers = [],
  backHref,
}: {
  mode: Mode
  course?: ElectiveCourseWithDetails
  subjects?: Option[]
  grades?: Option[]
  teachers?: Option[]
  backHref?: string
}) {
  const router = useRouter()
  const t = useTranslations("elective")
  const [isWorking, setIsWorking] = useState(false)

  const [subjectId, setSubjectId] = useState(course?.subjectId ?? "")
  const [gradeId, setGradeId] = useState(course?.gradeId ?? "")
  const [teacherId, setTeacherId] = useState(course?.teacherId ?? "")
  const [selectionMode, setSelectionMode] = useState<ElectiveSelectionMode>(course?.selectionMode ?? "fcfs")

  const handleSubmit = async (formData: FormData) => {
    setIsWorking(true)
    try {
      formData.set("subjectId", subjectId)
      formData.set("gradeId", gradeId)
      formData.set("teacherId", teacherId)
      formData.set("selectionMode", selectionMode)

      const res =
        mode === "create"
          ? await createElectiveCourseAction(null, formData)
          : course
            ? await updateElectiveCourseAction(course.id, null, formData)
            : null

      if (!res) {
        toast.error(t("form.invalidFormState"))
        return
      }

      if (res.success) {
        toast.success(res.message)
        // 根据 backHref 推断返回列表页路径
        const redirectBase = backHref?.includes("/teacher/") ? "/teacher/elective" : "/admin/elective"
        router.push(redirectBase)
        router.refresh()
      } else {
        toast.error(res.message || t("form.saveFailed"))
      }
    } catch {
      toast.error(t("form.saveFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === "create" ? t("form.createTitle") : t("form.editTitle")}
        </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 htmlFor="name">{t("form.nameLabel")}</Label>
              <Input
                id="name"
                name="name"
                required
                defaultValue={course?.name ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.subjectLabel")}</Label>
              <Select value={subjectId} onValueChange={setSubjectId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectSubjectPlaceholder")} />
                </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>{t("form.gradeLabel")}</Label>
              <Select value={gradeId} onValueChange={setGradeId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectGradePlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  {grades.map((g) => (
                    <SelectItem key={g.id} value={g.id}>
                      {g.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="gradeId" value={gradeId} />
            </div>

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

            <div className="grid gap-2">
              <Label htmlFor="capacity">{t("form.capacityLabel")}</Label>
              <Input
                id="capacity"
                name="capacity"
                type="number"
                min={1}
                max={500}
                defaultValue={course?.capacity ?? 30}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="classroom">{t("form.classroomLabel")}</Label>
              <Input
                id="classroom"
                name="classroom"
                defaultValue={course?.classroom ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="schedule">{t("form.scheduleLabel")}</Label>
              <Input
                id="schedule"
                name="schedule"
                placeholder={t("form.schedulePlaceholder")}
                defaultValue={course?.schedule ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="credit">{t("form.creditLabel")}</Label>
              <Input
                id="credit"
                name="credit"
                type="number"
                step="0.5"
                min={0}
                defaultValue={course?.credit ?? "1.0"}
              />
            </div>

            <div className="grid gap-2">
              <Label>{t("fields.selectionMode")}</Label>
              <Select
                value={selectionMode}
                onValueChange={(v) => {
                  if (isSelectionMode(v)) setSelectionMode(v)
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="fcfs">{t("selectionMode.fcfs")}</SelectItem>
                  <SelectItem value="lottery">{t("selectionMode.lottery")}</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="selectionMode" value={selectionMode} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="startDate">{t("form.startDateLabel")}</Label>
              <Input
                id="startDate"
                name="startDate"
                type="date"
                defaultValue={course?.startDate ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="endDate">{t("form.endDateLabel")}</Label>
              <Input
                id="endDate"
                name="endDate"
                type="date"
                defaultValue={course?.endDate ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="selectionStartAt">{t("form.selectionStartLabel")}</Label>
              <Input
                id="selectionStartAt"
                name="selectionStartAt"
                type="datetime-local"
                defaultValue={
                  course?.selectionStartAt
                    ? new Date(course.selectionStartAt).toISOString().slice(0, 16)
                    : ""
                }
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="selectionEndAt">{t("form.selectionEndLabel")}</Label>
              <Input
                id="selectionEndAt"
                name="selectionEndAt"
                type="datetime-local"
                defaultValue={
                  course?.selectionEndAt
                    ? new Date(course.selectionEndAt).toISOString().slice(0, 16)
                    : ""
                }
              />
            </div>

            {/* P2-4：退课截止时间 */}
            <div className="grid gap-2">
              <Label htmlFor="dropDeadline">{t("form.dropDeadlineLabel")}</Label>
              <Input
                id="dropDeadline"
                name="dropDeadline"
                type="datetime-local"
                defaultValue={
                  course?.dropDeadline
                    ? new Date(course.dropDeadline).toISOString().slice(0, 16)
                    : ""
                }
              />
              <p className="text-xs text-muted-foreground">
                {t("form.dropDeadlineHint")}
              </p>
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="description">{t("form.descriptionLabel")}</Label>
            <Textarea
              id="description"
              name="description"
              placeholder={t("form.descriptionPlaceholder")}
              className="min-h-[80px]"
              defaultValue={course?.description ?? ""}
            />
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button
              type="button"
              variant="outline"
              asChild
            >
              <Link href={backHref ?? "/admin/elective"}>{t("form.cancelButton")}</Link>
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? t("form.savingButton") : mode === "create" ? t("form.createButton") : t("form.saveButton")}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
