import { FC, useState } from "react";

import { feedbackToast } from "@/utils/common";

import { IMessageItemProps } from ".";

const formatFileSize = (size: number) => {
  if (!size && size !== 0) return "";
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`;
  return `${(size / 1024 / 1024 / 1024).toFixed(1)} GB`;
};

const FileIcon = () => (
  <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-[var(--primary-active)]">
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <path
        d="M6 2.5h8L19 7.5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-17a1 1 0 0 1 1-1Z"
        stroke="var(--primary)"
        strokeWidth="1.6"
        fill="#fff"
      />
      <path d="M13.5 2.5v5.5H19" stroke="var(--primary)" strokeWidth="1.6" fill="none" />
      <path
        d="M8.5 12h7M8.5 15.5h7"
        stroke="var(--primary)"
        strokeWidth="1.4"
        strokeLinecap="round"
      />
    </svg>
  </div>
);

const FileMessageRender: FC<IMessageItemProps> = ({ message }) => {
  const [downloading, setDownloading] = useState(false);
  const fileElem = message.fileElem;

  const saveFile = async () => {
    if (!fileElem || downloading) return;
    setDownloading(true);
    try {
      let url = fileElem.sourceUrl;
      let revoke = false;
      if (!url && fileElem.filePath && window.electronAPI) {
        const file = await window.electronAPI.getFileByPath(fileElem.filePath);
        if (file) {
          url = URL.createObjectURL(file);
          revoke = true;
        }
      }
      if (!url) throw new Error("no file url");

      const link = document.createElement("a");
      link.href = url;
      link.download = fileElem.fileName || "file";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      if (revoke) {
        setTimeout(() => URL.revokeObjectURL(url), 5000);
      }
    } catch (error) {
      feedbackToast({ error });
    } finally {
      setDownloading(false);
    }
  };

  if (!fileElem) return null;

  return (
    <div
      className="flex h-16 w-[280px] cursor-pointer items-center rounded-lg bg-white px-3"
      onClick={saveFile}
    >
      <FileIcon />
      <div className="ml-3 flex-1 overflow-hidden">
        <div className="truncate text-sm" title={fileElem.fileName}>
          {fileElem.fileName}
        </div>
        <div className="mt-0.5 text-xs text-[var(--sub-text)]">
          {formatFileSize(fileElem.fileSize)}
        </div>
      </div>
    </div>
  );
};

export default FileMessageRender;
