"use client";

import { useState, useEffect } from "react";
import { Download, CheckCircle2, Loader2 } from "lucide-react";
import {
  getSavedDownloads,
  saveDownload,
  type DownloadEntry,
} from "@/utils/downloads";

interface DownloadButtonProps {
  contentId: string;
  contentType: number;
  title: string;
  thumbnail: string;
  url: string;
  className?: string;
}

export default function DownloadButton({
  contentId,
  contentType,
  title,
  thumbnail,
  url,
  className = "",
}: DownloadButtonProps) {
  const [isDownloaded, setIsDownloaded] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);

  useEffect(() => {
    const saved = getSavedDownloads();
    setIsDownloaded(saved.some((d) => d.id === contentId));
  }, [contentId]);

  const handleDownload = async () => {
    if (isDownloaded || isDownloading) return;

    setIsDownloading(true);

    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const objectUrl = URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = objectUrl;
      a.download = title || "download";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(objectUrl);

      const entry: DownloadEntry = {
        id: contentId,
        contentType,
        title,
        thumbnail,
        url,
        downloadedAt: new Date().toISOString(),
      };
      saveDownload(entry);
      setIsDownloaded(true);
    } catch {
      // silently fail — user sees no change
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <button
      onClick={handleDownload}
      disabled={isDownloaded || isDownloading}
      title={isDownloaded ? "Already downloaded" : "Download"}
      className={`flex items-center justify-center rounded-lg transition-all duration-200 active:scale-95 disabled:cursor-default ${className}`}
      style={{
        background: isDownloaded
          ? "rgba(16,185,129,0.12)"
          : "rgba(var(--accent-rgb),0.1)",
        border: `1px solid ${isDownloaded ? "rgba(16,185,129,0.2)" : "rgba(var(--accent-rgb),0.2)"}`,
        color: isDownloaded ? "#10b981" : "var(--accent)",
        width: 36,
        height: 36,
      }}
    >
      {isDownloading ? (
        <Loader2 size={15} className="animate-spin" />
      ) : isDownloaded ? (
        <CheckCircle2 size={15} strokeWidth={2} />
      ) : (
        <Download size={15} strokeWidth={2} />
      )}
    </button>
  );
}
