'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Download,
  Loader2,
} from 'lucide-react';
import { api } from '@/lib/api';
import { useToast } from '@/hooks/use-toast';

interface DownloadMenuProps {
  documentId: string;
  documentName: string;
  serviceTier?: 'ai_text' | 'ai_ocr' | 'ai_human' | 'certified';
  isCompleted?: boolean;
  fileUrl?: string; // Direct file URL if available
}

/**
 * Simplified download component that provides DIRECT DOWNLOAD of the translated PDF.
 *
 * Per Peter's requirement (2025-12-24):
 * - Translated documents should work like source documents - DIRECT DOWNLOAD
 * - Documents are PRE-GENERATED when order completes (not generated on-demand)
 * - No /generate API call needed - file already exists
 * - Just download the existing file directly
 *
 * This matches the behavior of source document downloads: simple, direct, no generation step.
 */
export function DownloadMenu({
  documentId,
  documentName,
  serviceTier = 'ai_ocr',
  isCompleted = true,
  fileUrl
}: DownloadMenuProps) {
  const { toast } = useToast();
  const [downloading, setDownloading] = useState(false);

  const handleDownload = async () => {
    setDownloading(true);

    try {
      // If we have a direct file URL, use it (fastest method)
      if (fileUrl) {
        // Create a temporary link to download the file
        const a = document.createElement('a');
        a.href = fileUrl;
        a.download = documentName;
        a.target = '_blank'; // Open in new tab to handle CORS issues
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

        toast({
          title: 'Download started',
          description: 'PDF file download started',
        });
      } else {
        // Fallback: Fetch the translated PDF via API
        // Note: This does NOT call /generate - it fetches the existing file
        toast({
          title: 'Preparing download...',
          description: 'Fetching translated PDF',
        });

        // Download the pre-generated translated PDF directly
        // The document should have file_url_translated populated when order completed
        const blob = await api.downloadDocument(documentId);

        // Create download link
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = documentName;

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        toast({
          title: 'Download complete',
          description: 'PDF file downloaded successfully',
        });
      }
    } catch (error: any) {
      // Provide helpful error messages
      let title = 'Download failed';
      let description = error.message || 'Failed to download file';

      if (error.code === 'NOT_FOUND' || error.status === 404) {
        title = 'File not found';
        description = 'The translated document file could not be found. The translation may still be processing.';
      } else if (error.code === 'NETWORK_ERROR') {
        description = 'Network error. Please check your connection and try again.';
      }

      toast({
        title,
        description,
        variant: 'destructive',
      });
    } finally {
      setDownloading(false);
    }
  };

  if (!isCompleted) {
    return (
      <Button size="sm" disabled>
        <Download className="mr-2 h-4 w-4" />
        Processing...
      </Button>
    );
  }

  return (
    <Button size="sm" onClick={handleDownload} disabled={downloading}>
      {downloading ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          Downloading...
        </>
      ) : (
        <>
          <Download className="mr-2 h-4 w-4" />
          Download PDF
        </>
      )}
    </Button>
  );
}
