"use client";

import { useState } from "react";
import BoldIcon from "@/components/ui/BoldIcon";
import IOSSpinner from "@/components/ui/IOSSpinner";
import { cn } from "@/lib/utils";

interface FileMessageBubbleProps {
  url: string;
  fileName?: string;
  isOutgoing?: boolean;
}

/** Telegram-style file message with upload/download progress */
export default function FileMessageBubble({
  url,
  fileName = "فایل پیوست",
  isOutgoing = false,
}: FileMessageBubbleProps) {
  const [progress, setProgress] = useState(0);
  const [downloading, setDownloading] = useState(false);
  const isPending = url.startsWith("blob:");

  const handleDownload = async () => {
    if (downloading) return;
    setDownloading(true);
    setProgress(0);
    try {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onprogress = (e) => {
        if (e.lengthComputable) {
          setProgress(Math.round((e.loaded / e.total) * 100));
        }
      };
      xhr.onload = () => {
        if (xhr.status === 200) {
          const a = document.createElement("a");
          a.href = URL.createObjectURL(xhr.response);
          a.download = fileName;
          a.click();
          setProgress(100);
        }
        setDownloading(false);
      };
      xhr.onerror = () => {
        window.open(url, "_blank");
        setDownloading(false);
      };
      xhr.send();
    } catch {
      window.open(url, "_blank");
      setDownloading(false);
    }
  };

  return (
    <div
      className={cn(
        "flex min-w-[200px] max-w-[260px] items-center gap-3 rounded-2xl p-3",
        isOutgoing
          ? "bg-[#2aabee]/10"
          : "bg-neutral-50 dark:bg-neutral-800/80"
      )}
    >
      <div
        className={cn(
          "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl",
          isOutgoing ? "bg-[#2aabee]/20 text-[#2aabee]" : "bg-blue-500/15 text-blue-500"
        )}
      >
        {isPending || downloading ? (
          <IOSSpinner size={22} color={isOutgoing ? "#2aabee" : "#007aff"} />
        ) : (
          <BoldIcon name="document" size={22} tinted className="text-current" />
        )}
      </div>
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium">{fileName}</p>
        {(isPending || downloading) && (
          <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-700">
            <div
              className="gentle-transition h-full rounded-full bg-[#2aabee]"
              style={{ width: `${isPending ? 40 : progress}%` }}
            />
          </div>
        )}
        <span className="text-[10px] text-neutral-500">
          {isPending ? "در حال آپلود…" : downloading ? `${progress}%` : "فایل"}
        </span>
      </div>
      {!isPending && (
        <button
          type="button"
          onClick={handleDownload}
          className="gentle-transition rounded-full p-2 text-neutral-500 hover:bg-neutral-200/80 active:scale-90 dark:hover:bg-neutral-700"
          aria-label="دانلود"
        >
          <BoldIcon name="document-download" size={20} tinted className="text-current" />
        </button>
      )}
    </div>
  );
}
