"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 { createChapterAction } from "../actions"
import { toast } from "sonner"

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

interface CreateChapterDialogProps {
  textbookId: string
  parentId?: string
  trigger?: React.ReactNode | null
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

export function CreateChapterDialog({
  textbookId,
  parentId,
  trigger,
  open: controlledOpen,
  onOpenChange,
}: CreateChapterDialogProps) {
  const t = useTranslations("textbooks")
  const [uncontrolledOpen, setUncontrolledOpen] = useState(false)
  const open = controlledOpen ?? uncontrolledOpen
  const setOpen = onOpenChange ?? setUncontrolledOpen

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

  const triggerNode =
    trigger === null
      ? null
      : trigger || (
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-muted-foreground hover:text-foreground"
          >
            <Plus className="h-4 w-4" />
            <span className="sr-only">{t("dialog.chapter.createTitle")}</span>
          </Button>
        )

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {triggerNode ? <DialogTrigger asChild>{triggerNode}</DialogTrigger> : null}
      {/* 任意值 sm:max-w-[425px]：shadcn/ui Dialog 标准宽度约定 */}
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("dialog.chapter.createTitle")}</DialogTitle>
          <DialogDescription>{t("dialog.chapter.createDesc")}</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("dialog.chapter.titlePlaceholder")}
                className="col-span-3"
                required
              />
            </div>
          </div>
          <DialogFooter>
            <SubmitButton />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
