"use client"

import { useState } from "react"
import { Plus } from "lucide-react"
import { useFormStatus } from "react-dom"
import { useTranslations } from "next-intl"
import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
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 { createTextbookAction } from "../actions"
import { SUBJECTS, GRADES } from "../constants"
import { toast } from "sonner"

function SubmitButton() {
  const { pending } = useFormStatus()
  const t = useTranslations("textbooks")
  return (
    <Button type="submit" disabled={pending}>
      {pending ? t("dialog.create.saving") : t("dialog.create.submit")}
    </Button>
  )
}

export function TextbookFormDialog() {
  const t = useTranslations("textbooks")
  const [open, setOpen] = useState(false)

  const handleSubmit = async (formData: FormData) => {
    try {
      const result = await createTextbookAction(null, formData)
      if (result.success) {
        toast.success(result.message)
        setOpen(false)
      } else {
        toast.error(result.message)
      }
    } catch (e) {
      console.error("Failed to create textbook", e)
      toast.error(t("reader.createFailed"))
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="mr-2 h-4 w-4" />
          {t("list.add")}
        </Button>
      </DialogTrigger>
      {/* 任意值 sm:max-w-[425px]：shadcn/ui Dialog 标准宽度约定 */}
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("dialog.create.title")}</DialogTitle>
          <DialogDescription>{t("dialog.create.description")}</DialogDescription>
        </DialogHeader>
        <form action={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="title" className="text-right">
                {t("field.title")}
              </Label>
              <Input
                id="title"
                name="title"
                placeholder={t("field.titlePlaceholder")}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="subject" className="text-right">
                {t("field.subject")}
              </Label>
              <Select name="subject" required>
                <SelectTrigger className="col-span-3">
                  <SelectValue placeholder={t("field.subjectPlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  {SUBJECTS.map((s) => (
                    <SelectItem key={s.value} value={s.value}>
                      {t(`subject.${s.labelKey}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="grade" className="text-right">
                {t("field.grade")}
              </Label>
              <Select name="grade" required>
                <SelectTrigger className="col-span-3">
                  <SelectValue placeholder={t("field.gradePlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  {GRADES.map((g) => (
                    <SelectItem key={g.value} value={g.value}>
                      {t(`grade.${g.labelKey}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="publisher" className="text-right">
                {t("field.publisher")}
              </Label>
              <Input
                id="publisher"
                name="publisher"
                placeholder={t("field.publisherPlaceholder")}
                className="col-span-3"
              />
            </div>
          </div>
          <DialogFooter>
            <SubmitButton />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
