"use client"

import { File, HardDrive, Image as ImageIcon } from "lucide-react"
import { toast } from "sonner"
import type { EmailAttachment } from "@/lib/email-data"
import {
  mailAttachmentPreviewable,
  openMailAttachmentsPreview,
} from "@/lib/mail/mail-attachment-preview"

export function ListAttachmentChip({
  att,
  messageId,
  attachments,
  attachmentIndex,
}: {
  att: EmailAttachment
  messageId: string
  attachments: EmailAttachment[]
  attachmentIndex: number
}) {
  const onClick = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (!att.id) {
      toast.message("Pièce jointe non disponible")
      return
    }
    if (!mailAttachmentPreviewable(att)) {
      toast.message("Aperçu non disponible")
      return
    }
    openMailAttachmentsPreview(messageId, attachments, attachmentIndex)
  }

  return (
    <button
      type="button"
      onClick={onClick}
      className="inline-flex max-w-[min(100%,280px)] min-w-0 shrink items-center gap-1.5 rounded-full border border-mail-list-chip-border bg-transparent px-2.5 py-1 text-[13px] leading-snug text-mail-list-chip-text hover:bg-mail-list-chip-muted"
    >
      {att.kind === "pdf" ? (
        <File className="size-4 shrink-0 fill-destructive" strokeWidth={0} aria-hidden />
      ) : att.kind === "image" ? (
        <ImageIcon
          className="size-4 shrink-0 text-muted-foreground [&_circle]:fill-none [&_path]:fill-none [&_path]:stroke-current [&_rect]:fill-current [&_rect]:opacity-[0.32]"
          strokeWidth={1.5}
          aria-hidden
        />
      ) : (
        <File className="size-4 shrink-0 fill-muted-foreground" strokeWidth={0} aria-hidden />
      )}
      <span className="min-w-0 truncate">{att.name}</span>
      {att.drivePath ? (
        <HardDrive className="size-3.5 shrink-0 text-primary" aria-label="Dans UltiDrive" />
      ) : null}
    </button>
  )
}
