import { useMemo, useState } from "react";
import { Download, ExternalLink, FileIcon, ImageIcon } from "lucide-react";
import type { Particle } from "@/api/types";
import { useDownloadUrl } from "@/hooks/use-download-url";
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import {
  AttachmentLightbox,
  getAttachmentHandler,
  type AttachmentItem,
} from "@/features/attachments/attachment-lightbox";
import { platform } from "@/lib/platform";

type FileParticle = Extract<Particle, { type: "file" }>;

interface ParticleAttachmentsProps {
  attachments: FileParticle[];
  variant?: "inline" | "compact";
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function particleToItem(p: FileParticle): AttachmentItem {
  return {
    id: p.id,
    filename: p.properties.filename,
    mimeType: p.properties.mime_type,
    sizeBytes: p.properties.size_bytes,
    source: { kind: "remote", objectId: p.properties.object_id },
  };
}

/**
 * Open the lightbox for previewable types; hand off to the OS for files.
 */
function openParticle(
  particle: FileParticle,
  index: number,
  url: string | undefined,
  onPreview: (index: number) => void,
) {
  if (getAttachmentHandler(particle.properties.mime_type) === "lightbox") {
    onPreview(index);
  } else if (url) {
    platform.link.openExternal(url);
  }
}

function ImageAttachment({
  particle,
  onPreview,
}: {
  particle: FileParticle;
  onPreview: () => void;
}) {
  const { data: url, isLoading } = useDownloadUrl(particle.properties.object_id);

  if (isLoading || !url) {
    return <Skeleton className="h-20 w-20 shrink-0 rounded-lg bg-white/10" />;
  }

  const handleDownload = (e: React.MouseEvent) => {
    e.stopPropagation();
    platform.attachment.download(url, particle.properties.filename);
  };

  return (
    <button
      type="button"
      onClick={(e) => {
        e.stopPropagation();
        onPreview();
      }}
      className="group relative block h-30 w-40 shrink-0 overflow-hidden rounded-lg bg-white/10"
    >
      <img
        src={url}
        alt={particle.properties.filename}
        className="h-full w-full object-cover"
      />
      <span
        role="button"
        tabIndex={0}
        onClick={handleDownload}
        className="absolute bottom-1 right-1 rounded-full bg-black/60 p-1 text-white/70 opacity-0 transition-opacity hover:text-white group-hover:opacity-100"
      >
        <Download className="size-3.5" />
      </span>
    </button>
  );
}

function FileAttachment({
  particle,
  index,
  onPreview,
}: {
  particle: FileParticle;
  index: number;
  onPreview: (index: number) => void;
}) {
  const { data: url } = useDownloadUrl(particle.properties.object_id);

  const handleOpen = (e: React.MouseEvent) => {
    e.stopPropagation();
    openParticle(particle, index, url, onPreview);
  };

  const handleDownload = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!url) return;
    platform.attachment.download(url, particle.properties.filename);
  };

  return (
    <div
      role="button"
      onClick={handleOpen}
      className="flex shrink-0 cursor-pointer flex-col gap-1.5 rounded-lg bg-white/10 px-3 py-2 transition-colors hover:bg-white/15"
    >
      <div className="flex items-center gap-2">
        <FileIcon className="size-4 shrink-0 text-white/60" />
        <span className="max-w-[10rem] truncate text-xs font-medium text-white/90">
          {particle.properties.filename}
        </span>
        <span className="text-[10px] text-white/40">
          {formatFileSize(particle.properties.size_bytes)}
        </span>
      </div>
      <div className="flex gap-2">
        <Button
          variant="ghost"
          size="xs"
          className="text-white/70 hover:bg-white/10 hover:text-white"
          onClick={handleOpen}
        >
          <ExternalLink data-icon="inline-start" />
          Open
        </Button>
        <Button
          variant="ghost"
          size="xs"
          className="text-white/70 hover:bg-white/10 hover:text-white"
          onClick={handleDownload}
        >
          <Download data-icon="inline-start" />
          Download
        </Button>
      </div>
    </div>
  );
}

function CompactAttachmentItem({
  particle,
  index,
  onPreview,
}: {
  particle: FileParticle;
  index: number;
  onPreview: (index: number) => void;
}) {
  const isImage = particle.properties.mime_type.startsWith("image/");
  const { data: url } = useDownloadUrl(particle.properties.object_id);

  return (
    <button
      type="button"
      onClick={(e) => {
        e.stopPropagation();
        openParticle(particle, index, url, onPreview);
      }}
      className="flex w-full items-center gap-2 rounded-md bg-white/10 px-2.5 py-1.5 text-left transition-colors hover:bg-white/15"
    >
      {isImage ? (
        url ? (
          <img
            src={url}
            alt={particle.properties.filename}
            className="size-5 shrink-0 rounded object-cover"
          />
        ) : (
          <ImageIcon className="size-4 shrink-0 text-white/50" />
        )
      ) : (
        <FileIcon className="size-4 shrink-0 text-white/50" />
      )}
      <span className="min-w-0 truncate text-xs text-white/80">
        {particle.properties.filename}
      </span>
      <span className="shrink-0 text-[10px] text-white/40">
        {formatFileSize(particle.properties.size_bytes)}
      </span>
    </button>
  );
}

export function ParticleAttachments({ attachments, variant = "inline" }: ParticleAttachmentsProps) {
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  // Only previewable attachments populate the lightbox; the index passed to the
  // lightbox is the index into this filtered list, not `attachments`.
  const previewable = useMemo(
    () => attachments.filter((a) => getAttachmentHandler(a.properties.mime_type) === "lightbox"),
    [attachments],
  );
  const items = useMemo(() => previewable.map(particleToItem), [previewable]);

  const handlePreview = (attachmentIndex: number) => {
    const particle = attachments[attachmentIndex];
    if (!particle) return;
    const previewIdx = previewable.indexOf(particle);
    if (previewIdx >= 0) setOpenIndex(previewIdx);
  };

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

  const lightbox = items.length > 0 && (
    <AttachmentLightbox
      items={items}
      openIndex={openIndex}
      onOpenChange={setOpenIndex}
    />
  );

  if (variant === "compact") {
    return (
      <>
        <div className="flex max-w-48 flex-col gap-1">
          {attachments.map((attachment, i) => (
            <CompactAttachmentItem
              key={attachment.id}
              particle={attachment}
              index={i}
              onPreview={handlePreview}
            />
          ))}
        </div>
        {lightbox}
      </>
    );
  }

  return (
    <>
      <ScrollArea className="w-full">
        <div className="flex items-center gap-2 py-1">
          {attachments.map((attachment, i) => {
            const isImage = attachment.properties.mime_type.startsWith("image/");
            return isImage ? (
              <ImageAttachment
                key={attachment.id}
                particle={attachment}
                onPreview={() => handlePreview(i)}
              />
            ) : (
              <FileAttachment
                key={attachment.id}
                particle={attachment}
                index={i}
                onPreview={handlePreview}
              />
            );
          })}
        </div>
        <ScrollBar orientation="horizontal" />
      </ScrollArea>
      {lightbox}
    </>
  );
}
