"use client"

import { useState } from "react"
import Link from "next/link"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { FileText, Loader2, Trash2 } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
import { cn, formatDate } from "@/shared/lib/utils"

import { deleteMessageDraftAction } from "../actions"
import type { MessageDraft } from "../types"

/**
 * P1-1: 草稿列表组件。
 *
 * 渲染用户的未发送草稿，支持"继续编辑"（带 draftId 参数回到 compose 页）
 * 和"删除草稿"操作。compose page 通过 RSC 获取初始草稿列表传入；
 * 删除操作通过 Server Action 调用，使用乐观更新 + 失败回滚。
 */
export function MessageDraftList({ drafts }: { drafts: MessageDraft[] }) {
  const t = useTranslations("messages")
  const [items, setItems] = useState<MessageDraft[]>(drafts)
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [deleteOpen, setDeleteOpen] = useState<string | null>(null)

  const handleDelete = async (draftId: string) => {
    setDeletingId(draftId)
    // 乐观更新：立即从列表移除
    const snapshot = items
    setItems((prev) => prev.filter((d) => d.id !== draftId))
    try {
      const res = await deleteMessageDraftAction(draftId)
      if (!res.success) {
        // 回滚
        setItems(snapshot)
        toast.error(res.message)
      } else {
        toast.success(t("messages.draftDeleted"))
      }
    } catch {
      setItems(snapshot)
      toast.error(t("messages.sendFailed"))
    } finally {
      setDeletingId(null)
      setDeleteOpen(null)
    }
  }

  if (items.length === 0) {
    return (
      <Card className="border-dashed">
        <CardContent className="py-6">
          <EmptyState
            icon={FileText}
            title={t("empty.noDrafts")}
            description={t("empty.inboxEmptyDesc")}
            className="h-auto border-none shadow-none"
          />
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base">
          <FileText className="h-4 w-4" aria-hidden="true" />
          {t("drafts.title")}
          <span className="text-muted-foreground text-xs">({items.length})</span>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-2">
        {items.map((draft) => {
          const draftHref = draft.receiverId
            ? `/messages/compose?draftId=${encodeURIComponent(draft.id)}&receiverId=${encodeURIComponent(draft.receiverId)}${
                draft.subject ? `&subject=${encodeURIComponent(draft.subject)}` : ""
              }`
            : `/messages/compose?draftId=${encodeURIComponent(draft.id)}`
          return (
            <div
              key={draft.id}
              className={cn(
                "flex items-start justify-between gap-3 rounded-md border p-3 transition-colors hover:bg-accent/50"
              )}
            >
              <div className="min-w-0 flex-1 space-y-1">
                <p className="truncate text-sm font-medium">
                  {draft.subject || t("meta.noSubject")}
                </p>
                <p className="text-muted-foreground line-clamp-1 text-xs">
                  {draft.content || t("drafts.noContent")}
                </p>
                <p className="text-muted-foreground text-xs">
                  {t("drafts.updatedAt", { date: formatDate(draft.updatedAt) })}
                </p>
              </div>
              <div className="flex shrink-0 items-center gap-1">
                <Button asChild variant="ghost" size="sm" aria-label={t("drafts.resume")}>
                  <Link href={draftHref}>{t("drafts.resume")}</Link>
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="text-muted-foreground hover:text-destructive"
                  onClick={() => setDeleteOpen(draft.id)}
                  disabled={deletingId === draft.id}
                  aria-label={t("drafts.delete")}
                >
                  {deletingId === draft.id ? (
                    <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
                  ) : (
                    <Trash2 className="h-4 w-4" aria-hidden="true" />
                  )}
                </Button>
              </div>
              <ConfirmDeleteDialog
                open={deleteOpen === draft.id}
                onOpenChange={(v) => setDeleteOpen(v ? draft.id : null)}
                title={t("drafts.delete")}
                description={t("empty.deleteDesc", { subject: draft.subject || t("meta.noSubject") })}
                onConfirm={() => handleDelete(draft.id)}
                isWorking={deletingId === draft.id}
              />
            </div>
          )
        })}
      </CardContent>
    </Card>
  )
}
