"use client"

import { useState } from "react"
import { Edit } from "lucide-react"
import { useRouter } from "next/navigation"
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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { updateTextbookAction, deleteTextbookAction } from "../actions"
import { toast } from "sonner"
import type { Textbook } from "../types"
import { TextbookFormFields } from "./textbook-form-fields"

interface TextbookSettingsDialogProps {
  textbook: Textbook
  trigger?: React.ReactNode
  /** 删除后跳转的 URL，默认 "/teacher/textbooks" */
  redirectAfterDelete?: string
}

export function TextbookSettingsDialog({ textbook, trigger, redirectAfterDelete = "/teacher/textbooks" }: TextbookSettingsDialogProps) {
  const t = useTranslations("textbooks")
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const router = useRouter()

  const handleUpdate = async (formData: FormData) => {
    setLoading(true)
    try {
      const result = await updateTextbookAction(textbook.id, null, formData)
      if (result.success) {
        toast.success(result.message)
        setOpen(false)
      } else {
        toast.error(result.message)
      }
    } catch (e) {
      console.error("Failed to update textbook", e)
      toast.error(t("reader.updateFailed"))
    } finally {
      setLoading(false)
    }
  }

  // P1-8 用 AlertDialog 替换浏览器原生 confirm()
  const handleDelete = async () => {
    setDeleteDialogOpen(false)
    setLoading(true)
    try {
      const result = await deleteTextbookAction(textbook.id)

      if (result.success) {
        toast.success(result.message)
        router.push(redirectAfterDelete)
      } else {
        toast.error(result.message)
      }
    } catch (e) {
      console.error("Failed to delete textbook", e)
      toast.error(t("reader.deleteFailed"))
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" size="sm">
            <Edit className="mr-2 h-4 w-4" />
            {t("dialog.settings.trigger")}
          </Button>
        )}
      </DialogTrigger>
      {/* 任意值 sm:max-w-[425px]：shadcn/ui Dialog 标准宽度约定 */}
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("dialog.settings.title")}</DialogTitle>
          <DialogDescription>{t("dialog.settings.description")}</DialogDescription>
        </DialogHeader>

        <form action={handleUpdate}>
          <TextbookFormFields
            defaultValues={{
              title: textbook.title,
              subject: textbook.subject,
              grade: textbook.grade,
              publisher: textbook.publisher,
            }}
          />

          <DialogFooter className="flex justify-between sm:justify-between">
            <Button
              type="button"
              variant="destructive"
              onClick={() => setDeleteDialogOpen(true)}
              disabled={loading}
            >
              {loading ? t("dialog.settings.processing") : t("dialog.settings.delete")}
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? t("dialog.settings.processing") : t("dialog.settings.save")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("dialog.settings.deleteConfirmTitle")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("dialog.settings.deleteConfirmDesc")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("dialog.knowledge.cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>
              {t("dialog.settings.delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Dialog>
  )
}
