"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Paperclip, X, FileText, Loader2, Download } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { formatFileSize } from "@/shared/lib/file-storage"
import { useFileUpload, type UploadTask } from "@/modules/files/hooks/use-file-upload"
import type { FileUploadResult } from "@/modules/files/types"

import type { MessageAttachment } from "../types"

const MESSAGE_TARGET_TYPE = "message"

/**
 * P2-3: 消息附件上传区（compose 用）。
 *
 * 采用临时上传模式：targetType="message" + targetId="draft-{userId}-{timestamp}"。
 * 发送消息后由 Server Action 通过 updateFileTargets 批量更新 targetId 为真实 messageId。
 *
 * 为简化实现，本组件仅返回上传后的附件 ID 列表，由 compose form 提交时一并传入。
 */
export function MessageAttachmentUploader({
  onAttachmentsChange,
}: {
  onAttachmentsChange: (attachments: FileUploadResult[]) => void
}) {
  const t = useTranslations("messages")
  const [attachments, setAttachments] = useState<FileUploadResult[]>([])
  // 临时 targetId：使用 useState 懒初始化避免渲染期间调用 Date.now()（react-hooks/purity）
  const [draftTargetId] = useState(() => `draft-${Date.now()}`)

  const { tasks, inputRef, handleFiles, removeTask, acceptAttr } = useFileUpload({
    targetType: MESSAGE_TARGET_TYPE,
    // 临时 targetId，发送时由 action 更新为真实 messageId
    targetId: draftTargetId,
    multiple: true,
    onUploaded: (result) => {
      const next = [...attachments, result]
      setAttachments(next)
      onAttachmentsChange(next)
    },
  })

  const handleRemove = (task: UploadTask): void => {
    removeTask(task)
    if (task.result) {
      const next = attachments.filter((a) => a.id !== task.result!.id)
      setAttachments(next)
      onAttachmentsChange(next)
    }
  }

  return (
    <div className="space-y-2">
      <input
        ref={inputRef}
        type="file"
        multiple
        accept={acceptAttr}
        className="hidden"
        onChange={(e) => handleFiles(e.target.files)}
      />
      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={() => inputRef.current?.click()}
      >
        <Paperclip className="mr-2 h-4 w-4" aria-hidden="true" />
        {t("attachments.add")}
      </Button>

      {/* 上传任务列表 */}
      {tasks.length > 0 ? (
        <ul className="space-y-1">
          {tasks.map((task) => (
            <li
              key={`${task.file.name}-${task.file.lastModified}`}
              className="bg-muted/40 flex items-center justify-between gap-2 rounded px-2 py-1 text-sm"
            >
              <div className="flex min-w-0 items-center gap-2">
                {task.status === "uploading" ? (
                  <Loader2 className="h-3 w-3 shrink-0 animate-spin" aria-hidden="true" />
                ) : (
                  <FileText className="text-muted-foreground h-3 w-3 shrink-0" aria-hidden="true" />
                )}
                <span className="truncate">{task.file.name}</span>
                <span className="text-muted-foreground shrink-0 text-xs">
                  {formatFileSize(task.file.size)}
                </span>
                {task.status === "error" && task.message ? (
                  <span className="text-destructive shrink-0 text-xs">{task.message}</span>
                ) : null}
              </div>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={() => handleRemove(task)}
                aria-label={t("attachments.remove")}
              >
                <X className="h-3 w-3" aria-hidden="true" />
              </Button>
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  )
}

/**
 * P2-3: 消息附件列表展示（detail 用）。
 *
 * 只读展示已上传附件，提供下载链接。
 */
export function MessageAttachmentList({
  attachments,
}: {
  attachments: MessageAttachment[]
}) {
  const t = useTranslations("messages")

  if (attachments.length === 0) return null

  return (
    <div className="space-y-2">
      <div className="text-muted-foreground flex items-center gap-1 text-sm font-medium">
        <Paperclip className="h-3 w-3" aria-hidden="true" />
        {t("attachments.title", { count: attachments.length })}
      </div>
      <ul className="space-y-1">
        {attachments.map((a) => (
          <li
            key={a.id}
            className="bg-muted/40 flex items-center justify-between gap-2 rounded px-2 py-1 text-sm"
          >
            <div className="flex min-w-0 items-center gap-2">
              <FileText className="text-muted-foreground h-3 w-3 shrink-0" aria-hidden="true" />
              <span className="truncate">{a.originalName}</span>
              <span className="text-muted-foreground shrink-0 text-xs">
                {formatFileSize(a.size)}
              </span>
            </div>
            {a.url ? (
              <Button asChild variant="ghost" size="icon" className="h-6 w-6">
                <a
                  href={a.url}
                  download={a.originalName}
                  target="_blank"
                  rel="noopener noreferrer"
                  aria-label={t("attachments.download")}
                >
                  <Download className="h-3 w-3" aria-hidden="true" />
                </a>
              </Button>
            ) : null}
          </li>
        ))}
      </ul>
    </div>
  )
}
