"use client"

import { useState } from "react"
import { Download, Trash2, FileWarning } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"
import { formatFileSize } from "@/shared/lib/file-storage"
import { FileIcon } from "./file-icon"
import type { FileAttachment } from "../types"

interface FileListProps {
  files: FileAttachment[]
  canDelete?: boolean
  onDeleted?: (id: string) => void
  emptyTitle?: string
  emptyDescription?: string
}

export function FileList({
  files,
  canDelete = false,
  onDeleted,
  emptyTitle = "No files",
  emptyDescription = "There are no files yet.",
}: FileListProps) {
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const handleDelete = async (file: FileAttachment) => {
    setDeletingId(file.id)
    try {
      const res = await fetch(`/api/files/${file.id}`, { method: "DELETE" })
      const body = await res.json().catch(() => null)
      if (!res.ok || !body?.success) {
        toast.error(body?.message || "Failed to delete file")
        return
      }
      toast.success("File deleted")
      onDeleted?.(file.id)
    } catch {
      toast.error("Failed to delete file")
    } finally {
      setDeletingId(null)
    }
  }

  if (files.length === 0) {
    return (
      <EmptyState
        title={emptyTitle}
        description={emptyDescription}
        icon={FileWarning}
        className="h-auto border-none shadow-none"
      />
    )
  }

  return (
    <ul className="divide-y rounded-md border">
      {files.map((file) => (
        <li
          key={file.id}
          className="flex items-center gap-3 p-3 transition-colors hover:bg-accent/40"
        >
          <FileIcon mimeType={file.mimeType} className="h-6 w-6" />
          <div className="min-w-0 flex-1">
            <div className="flex items-center justify-between gap-2">
              <a
                href={file.url ?? "#"}
                target="_blank"
                rel="noopener noreferrer"
                className="truncate text-sm font-medium hover:underline"
                title={file.originalName}
              >
                {file.originalName}
              </a>
              <span className="shrink-0 text-xs text-muted-foreground">
                {formatFileSize(file.size)}
              </span>
            </div>
            <div className="mt-0.5 flex items-center gap-2 text-xs text-muted-foreground">
              <span className="font-mono">{file.mimeType}</span>
              <span>·</span>
              <span>{formatDate(file.createdAt, "zh-CN")}</span>
            </div>
          </div>
          <div className="flex shrink-0 items-center gap-1">
            <Button
              asChild
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              title="Download"
            >
              <a
                href={file.url ?? "#"}
                download={file.originalName}
                target="_blank"
                rel="noopener noreferrer"
              >
                <Download className="h-4 w-4" />
                <span className="sr-only">Download</span>
              </a>
            </Button>
            {canDelete ? (
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-destructive hover:text-destructive"
                title="Delete"
                disabled={deletingId === file.id}
                onClick={() => void handleDelete(file)}
              >
                <Trash2 className="h-4 w-4" />
                <span className="sr-only">Delete</span>
              </Button>
            ) : null}
          </div>
        </li>
      ))}
    </ul>
  )
}
