import { LoaderCircle } from "lucide-react";
import { DownloadCloudIcon } from "../icons/DownloadCloudIcon";
import { useState, type MouseEvent } from "react";
import { useI18n } from "../../i18n";
import type { Attachment } from "../../types/post";
import { downloadAttachment } from "./utils/downloadFile";
import { formatBytes } from "./utils/formatBytes";
import { useToast } from "../Toast";

type AttachmentDownloadPillProps = {
  postId: string;
  attachment: Attachment;
  leadingLabel?: string;
  className?: string;
};

export function AttachmentDownloadPill({
  postId,
  attachment,
  leadingLabel,
  className = "absolute left-2 top-2",
}: AttachmentDownloadPillProps) {
  const { t } = useI18n();
  const { showToast } = useToast();
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownload = async (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    if (isDownloading) return;
    setIsDownloading(true);
    try {
      await downloadAttachment(postId, attachment.id, attachment.filename);
      showToast(t("downloadOk"));
    } catch {
      showToast(t("downloadFail"), "error");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <button
      type="button"
      onClick={handleDownload}
      disabled={isDownloading}
      className={`group z-10 inline-flex overflow-hidden rounded-full bg-black/80 text-[12px] text-white shadow-lg ring-1 ring-inset ring-white/20 backdrop-blur-md transition hover:bg-black/90 disabled:cursor-wait ${className}`}
      aria-label={
        isDownloading ? t("downloading") : `Download ${attachment.filename}`
      }
      aria-busy={isDownloading}
    >
      <span className="flex h-[30px] w-[30px] items-center justify-center bg-[#545454]/50 transition group-hover:bg-[#545454]/70">
        {isDownloading ? (
          <LoaderCircle
            className="h-[18px] w-[18px] animate-spin"
            strokeWidth={2.3}
          />
        ) : (
          <DownloadCloudIcon className="h-[18px] w-[18px]" />
        )}
      </span>
      <span className="flex h-[30px] items-center gap-0.5 px-2.5">
        {isDownloading ? (
          t("downloading")
        ) : (
          <>
            {leadingLabel ? (
              <>
                <span>{leadingLabel}</span>
                <span className="opacity-60">·</span>
              </>
            ) : null}
            <span>{formatBytes(attachment.sizeBytes)}</span>
          </>
        )}
      </span>
    </button>
  );
}
