import React, { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Upload, FileText, Loader2, AlertCircle, X } from 'lucide-react';
import { parsePDFBill } from '@/lib/PDFBillParser';
import { cn } from '@/lib/utils';

export default function BillPDFUploadDialog({ open, onOpenChange, onParsed }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const onDrop = useCallback(async (acceptedFiles) => {
    const file = acceptedFiles[0];
    if (!file) return;

    if (file.size > 10 * 1024 * 1024) {
        setError("File is too large. Maximum size is 10MB.");
        return;
    }

    setLoading(true);
    setError(null);

    try {
        const result = await parsePDFBill(file);
        
        if (result.success) {
            onParsed(result.data, file);
            onOpenChange(false);
        } else {
            setError("Failed to extract data from PDF. Please try entering details manually.");
        }
    } catch (err) {
        console.error(err);
        setError("An unexpected error occurred while processing the file.");
    } finally {
        setLoading(false);
    }
  }, [onParsed, onOpenChange]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: { 'application/pdf': ['.pdf'] },
    maxFiles: 1,
    multiple: false
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Upload Bill PDF</DialogTitle>
          <DialogDescription>
            Upload a PDF invoice to automatically extract details.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Error</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <div
            {...getRootProps()}
            className={cn(
              "border-2 border-dashed rounded-lg p-10 text-center cursor-pointer transition-colors relative overflow-hidden",
              isDragActive ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:bg-muted/50",
              loading && "pointer-events-none opacity-60"
            )}
          >
            <input {...getInputProps()} />
            
            {loading ? (
                <div className="flex flex-col items-center justify-center space-y-3">
                    <Loader2 className="h-10 w-10 text-primary animate-spin" />
                    <p className="text-sm font-medium">Analyzing PDF...</p>
                </div>
            ) : (
                <div className="flex flex-col items-center justify-center space-y-3">
                    <div className="bg-muted p-3 rounded-full">
                        <Upload className="h-6 w-6 text-muted-foreground" />
                    </div>
                    <div className="space-y-1">
                        <p className="text-sm font-medium">Click to upload or drag and drop</p>
                        <p className="text-xs text-muted-foreground">PDF files only (max 10MB)</p>
                    </div>
                </div>
            )}
          </div>
          
          <div className="flex justify-center">
             <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)} disabled={loading}>
                 Cancel
             </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
