'use client';

import { useState } from 'react';
import { Download, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';

interface DocumentDownloadButtonProps {
  documentId: string;
}

export function DocumentDownloadButton({ documentId }: DocumentDownloadButtonProps) {
  const [loading, setLoading] = useState(false);

  async function handleDownload() {
    setLoading(true);
    try {
      const res = await fetch(`/api/portal/documents/${documentId}/download`);
      if (!res.ok) {
        toast.error('Unable to download document. Please try again.');
        return;
      }
      const data = (await res.json()) as { url: string };
      window.open(data.url, '_blank', 'noopener,noreferrer');
    } catch {
      toast.error('Unable to download document. Please check your connection.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <Button variant="outline" size="sm" onClick={handleDownload} disabled={loading}>
      {loading ? (
        <Loader2 className="h-3.5 w-3.5 animate-spin" />
      ) : (
        <>
          <Download className="h-3.5 w-3.5 mr-1.5" />
          Download
        </>
      )}
    </Button>
  );
}
