import { LoaderCircle } from "lucide-react";
import { useState } from "react";
import { DownloadCloudIcon } from "../icons/DownloadCloudIcon";
import { useI18n } from "../../i18n";
import {
  mediaSaveKindFromAttachment,
  useSaveToAlbumGuide,
} from "../SaveToAlbumGuide";
import { useToast } from "../Toast";
import type { Attachment } from "../../types/post";
import { downloadAttachment, pauseActiveVideos } from "./utils/downloadFile";
import { filenameWithExtension } from "./utils/filenameDisplay";

export function BubbleAttachmentDownloadButton({
  postId,
  attachment,
}: {
  postId: string;
  attachment: Attachment;
}) {
  const { t } = useI18n();
  const { showToast } = useToast();
  const { showSaveToAlbumGuide } = useSaveToAlbumGuide();
  const [isDownloading, setIsDownloading] = useState(false);
  const displayFilename = filenameWithExtension(
    attachment.filename,
    attachment.mime,
  );

  const handleDownload = async () => {
    if (isDownloading) return;
    pauseActiveVideos();
    setIsDownloading(true);
    try {
      await downloadAttachment(postId, attachment.id, displayFilename, {
        sizeBytes: attachment.sizeBytes,
      });
      const mediaKind = mediaSaveKindFromAttachment(attachment);
      if (mediaKind) showSaveToAlbumGuide(mediaKind);
    } catch {
      showToast(t("downloadFail"), "error");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <button
      type="button"
      onClick={(event) => {
        event.preventDefault();
        event.stopPropagation();
        void handleDownload();
      }}
      disabled={isDownloading}
      aria-label={
        isDownloading ? t("downloading") : `Download ${attachment.filename}`
      }
      aria-busy={isDownloading}
      className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-white/10 bg-[#191921]/90 text-[#A8A9AE] outline-none transition active:scale-95 hover:border-ark-gold hover:bg-[#191921] hover:text-ark-gold focus-visible:ring-2 focus-visible:ring-ark-gold/80 disabled:cursor-wait disabled:opacity-70"
    >
      {isDownloading ? (
        <LoaderCircle className="h-4 w-4 animate-spin" strokeWidth={2.2} />
      ) : (
        <DownloadCloudIcon className="h-5 w-5" />
      )}
    </button>
  );
}
