"use client"

import { useCallback, useEffect, useState } from "react"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { ChevronDown, FileText, Plus, Trash2 } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { cn, formatDate } from "@/shared/lib/utils"

import {
  deleteMessageTemplateAction,
  getMessageTemplatesAction,
  saveMessageTemplateAction,
} from "../actions"
import type { MessageTemplate } from "../types"

/**
 * P2-6: 快捷回复模板选择器
 *
 * 在 compose 页面展示"插入模板"下拉，点击模板追加到正文。
 * 内置模板管理弹窗（创建/编辑/删除）。
 */
export function MessageTemplatePicker({
  onInsert,
}: {
  onInsert: (content: string) => void
}) {
  const t = useTranslations("messages")
  const [templates, setTemplates] = useState<MessageTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [manageOpen, setManageOpen] = useState(false)
  const [editing, setEditing] = useState<MessageTemplate | null>(null)
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [sortOrder, setSortOrder] = useState("0")
  const [isSaving, setIsSaving] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const loadTemplates = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getMessageTemplatesAction()
      if (res.success && res.data) {
        setTemplates(res.data)
      } else {
        setTemplates([])
      }
    } catch {
      setTemplates([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadTemplates()
  }, [loadTemplates])

  const handleInsert = (template: MessageTemplate): void => {
    onInsert(template.content)
    toast.success(t("templates.insert"))
  }

  const openCreate = (): void => {
    setEditing(null)
    setTitle("")
    setContent("")
    setSortOrder("0")
    setManageOpen(true)
  }

  const openEdit = (template: MessageTemplate): void => {
    setEditing(template)
    setTitle(template.title)
    setContent(template.content)
    setSortOrder(String(template.sortOrder))
    setManageOpen(true)
  }

  const handleSave = async (formData: FormData): Promise<void> => {
    setIsSaving(true)
    try {
      const res = await saveMessageTemplateAction(null, formData)
      if (res.success) {
        toast.success(t("templates.saved"))
        setManageOpen(false)
        await loadTemplates()
      } else {
        toast.error(res.message)
      }
    } catch {
      toast.error(t("templates.saved"))
    } finally {
      setIsSaving(false)
    }
  }

  const handleDelete = async (templateId: string): Promise<void> => {
    setDeletingId(templateId)
    try {
      const res = await deleteMessageTemplateAction(templateId)
      if (res.success) {
        toast.success(t("templates.deleted"))
        await loadTemplates()
      } else {
        toast.error(res.message)
      }
    } catch {
      toast.error(t("templates.deleted"))
    } finally {
      setDeletingId(null)
    }
  }

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button type="button" variant="outline" size="sm" disabled={loading}>
            <FileText className="mr-2 h-4 w-4" />
            {t("templates.insert")}
            <ChevronDown className="ml-1 h-3 w-3" aria-hidden="true" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="start" className="w-72">
          <DropdownMenuLabel>{t("templates.title")}</DropdownMenuLabel>
          <DropdownMenuSeparator />
          {templates.length === 0 ? (
            <div className="text-muted-foreground px-2 py-3 text-sm">
              {t("templates.empty")}
            </div>
          ) : (
            templates.map((template) => (
              <DropdownMenuItem
                key={template.id}
                onClick={() => handleInsert(template)}
                className="flex flex-col items-start gap-1"
              >
                <span className="text-sm font-medium">{template.title}</span>
                <span className="text-muted-foreground line-clamp-1 text-xs">
                  {template.content}
                </span>
              </DropdownMenuItem>
            ))
          )}
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={openCreate}>
            <Plus className="mr-2 h-4 w-4" />
            {t("templates.create")}
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setManageOpen(true)}>
            <FileText className="mr-2 h-4 w-4" />
            {t("templates.manage")}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* 模板管理弹窗 */}
      <Dialog open={manageOpen} onOpenChange={setManageOpen}>
        <DialogContent className="max-h-[85vh] max-w-2xl overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editing ? t("templates.edit") : t("templates.create")}
            </DialogTitle>
            <DialogDescription>{t("templates.emptyDesc")}</DialogDescription>
          </DialogHeader>

          {/* 已有模板列表（编辑模式下显示在表单下方） */}
          {templates.length > 0 ? (
            <div className="space-y-2">
              {templates.map((template) => (
                <div
                  key={template.id}
                  className={cn(
                    "flex items-center justify-between gap-2 rounded-md border p-2",
                    editing?.id === template.id && "border-primary/40 bg-primary/5"
                  )}
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="truncate text-sm font-medium">{template.title}</span>
                      <span className="text-muted-foreground text-xs">
                        {formatDate(template.updatedAt)}
                      </span>
                    </div>
                    <p className="text-muted-foreground line-clamp-1 text-xs">
                      {template.content}
                    </p>
                  </div>
                  <div className="flex shrink-0 gap-1">
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => openEdit(template)}
                    >
                      {t("templates.edit")}
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => void handleDelete(template.id)}
                      disabled={deletingId === template.id}
                      aria-label={t("templates.delete")}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">{t("templates.empty")}</p>
          )}

          {/* 新建/编辑表单 */}
          <form action={handleSave} className="space-y-4 pt-2">
            {editing ? (
              <input type="hidden" name="templateId" value={editing.id} />
            ) : null}
            <div className="grid gap-2">
              <Label htmlFor="template-title">{t("templates.titleField")}</Label>
              <Input
                id="template-title"
                name="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder={t("templates.titlePlaceholder")}
                maxLength={100}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="template-content">{t("templates.contentField")}</Label>
              <Textarea
                id="template-content"
                name="content"
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder={t("templates.contentPlaceholder")}
                className="min-h-[100px]"
                maxLength={2000}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="template-sort">{t("templates.sortOrder")}</Label>
              <Input
                id="template-sort"
                name="sortOrder"
                type="number"
                min={0}
                max={9999}
                value={sortOrder}
                onChange={(e) => setSortOrder(e.target.value)}
              />
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setManageOpen(false)}
                disabled={isSaving}
              >
                {t("actions.cancel")}
              </Button>
              <Button type="submit" disabled={isSaving}>
                {t("actions.saveDraft")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  )
}
