"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 { createTextbookAction } from "../actions"
import { toast } from "sonner"
import { TextbookFormFields } from "./textbook-form-fields"

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}>
          <TextbookFormFields />
          <DialogFooter>
            <SubmitButton />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
