import React, { useMemo } from "react";
import {
  X,
  FileText,
  Image as ImageIcon,
  Film,
  File,
  FileSpreadsheet,
} from "lucide-react";

/**
 * Renders a preview chip for an attached file.
 * Used both in the pending-files area (before send) and in message bubbles (after send).
 *
 * Props:
 *   file?: File object (for pending uploads — generates preview from File API)
 *   attachment?: { filename, mime_type, file_size, media_type, preview_url } (for sent messages)
 *   onRemove?: () => void (if removable)
 *   isPending?: boolean (styling difference)
 */
export default function AttachmentPreview({
  file,
  attachment,
  onRemove,
  isPending,
}) {
  const info = useMemo(() => {
    if (file) {
      return {
        name: file.name,
        size: file.size,
        type: file.type,
        mediaType: classifyMime(file.type),
        previewUrl: file.type.startsWith("image/")
          ? URL.createObjectURL(file)
          : null,
      };
    }
    if (attachment) {
      return {
        name: attachment.filename || attachment.original_filename || "file",
        size: attachment.file_size,
        type: attachment.mime_type,
        mediaType: attachment.media_type,
        previewUrl: attachment.preview_url || null,
      };
    }
    return { name: "unknown", size: 0, type: "", mediaType: "unknown", previewUrl: null };
  }, [file, attachment]);

  const Icon = getIcon(info.mediaType);
  const sizeStr = formatSize(info.size);

  return (
    <div
      className={`
      group relative flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-xs
      ${
        isPending
          ? "bg-anton-card border-anton-accent/30 text-anton-text"
          : "bg-anton-surface border-anton-border text-anton-muted"
      }
      transition hover:border-anton-accent/50
    `}
    >
      {/* Image thumbnail */}
      {info.previewUrl && info.mediaType === "image" ? (
        <img
          src={info.previewUrl}
          alt={info.name}
          className="w-8 h-8 rounded object-cover flex-shrink-0"
          onLoad={() => {
            // Revoke blob URL after load to free memory (only for pending files)
            if (file && info.previewUrl) {
              // Don't revoke immediately — component might re-render
            }
          }}
        />
      ) : (
        <Icon
          size={16}
          className={`flex-shrink-0 ${
            isPending ? "text-anton-accent" : "text-anton-muted"
          }`}
        />
      )}

      <div className="flex flex-col min-w-0">
        <span className="truncate max-w-[140px] font-medium">{info.name}</span>
        <span className="text-[10px] text-anton-muted">{sizeStr}</span>
      </div>

      {/* Remove button */}
      {onRemove && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onRemove();
          }}
          className="ml-1 p-0.5 rounded-full text-anton-muted hover:text-anton-danger hover:bg-anton-danger/10 transition opacity-0 group-hover:opacity-100"
          title="Remove"
        >
          <X size={12} />
        </button>
      )}

      {/* Video badge */}
      {info.mediaType === "video" && (
        <span className="absolute -top-1 -right-1 bg-anton-accent text-white text-[9px] font-bold px-1 rounded">
          VID
        </span>
      )}
    </div>
  );
}

function classifyMime(mime) {
  if (!mime) return "unknown";
  if (mime.startsWith("image/")) return "image";
  if (mime.startsWith("video/")) return "video";
  if (
    mime === "application/pdf" ||
    mime.includes("word") ||
    mime.includes("document")
  )
    return "document";
  if (
    mime.includes("excel") ||
    mime.includes("spreadsheet") ||
    mime === "text/csv"
  )
    return "spreadsheet";
  if (mime.startsWith("text/")) return "text";
  return "unknown";
}

function getIcon(mediaType) {
  switch (mediaType) {
    case "image":
      return ImageIcon;
    case "video":
      return Film;
    case "document":
      return FileText;
    case "spreadsheet":
      return FileSpreadsheet;
    case "text":
      return FileText;
    default:
      return File;
  }
}

function formatSize(bytes) {
  if (!bytes || bytes === 0) return "0 B";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}