import React, { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Alert, AlertTitle, AlertDescription } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import { Upload, FileText, AlertTriangle, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { validateCSVHeaders, validateRow, parseCSVFile, consolidateRows } from '@/lib/delinquencyImportUtils';
import { supabase } from '@/integrations/supabase/client';

export default function ImportDelinquencyDialog({ open, onOpenChange, associationId, onSuccess }) {
  const [file, setFile] = useState(null);
  const [analyzing, setAnalyzing] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [validationResult, setValidationResult] = useState(null);
  const [parsedRows, setParsedRows] = useState([]);
  const { toast } = useToast();

  const onDrop = useCallback(async (acceptedFiles) => {
    const selectedFile = acceptedFiles[0];
    if (!selectedFile) return;
    
    setFile(selectedFile);
    setAnalyzing(true);
    setValidationResult(null);

    try {
      const rows = await parseCSVFile(selectedFile);
      
      if (rows.length === 0) throw new Error("File is empty");
      const headers = Object.keys(rows[0]);
      const headerCheck = validateCSVHeaders(headers);
      
      if (!headerCheck.valid) {
        setValidationResult({ valid: false, error: headerCheck.error });
        setAnalyzing(false);
        return;
      }

      const errors = [];
      let validRows = 0;

      rows.forEach((row, index) => {
        const rowErrors = validateRow(row, index);
        if (rowErrors.length > 0) {
          errors.push(...rowErrors);
        } else {
          validRows++;
        }
      });

      setParsedRows(rows);
      setValidationResult({
        valid: errors.length === 0,
        totalRows: rows.length,
        validRows,
        errors
      });

    } catch (error) {
      setValidationResult({ valid: false, error: error.message });
    } finally {
      setAnalyzing(false);
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: { 'text/csv': ['.csv'] },
    maxFiles: 1
  });

  const handleImport = async () => {
    if (!parsedRows.length || !associationId) return;
    setUploading(true);

    try {
      const consolidated = consolidateRows(parsedRows);

      const { data, error } = await supabase.functions.invoke('process-delinquency-import', {
        body: { rows: consolidated, association_id: associationId }
      });

      if (error) throw new Error(error.message);
      if (!data.success) throw new Error(data.error);

      toast({
        title: "Import Successful",
        description: `Processed ${data.processed} records with ${data.errors} errors.`
      });

      if (onSuccess) onSuccess();
      onOpenChange(false);
      setFile(null);
      setValidationResult(null);

    } catch (err) {
      toast({
        variant: "destructive",
        title: "Import Failed",
        description: err.message
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Import Delinquency Records</DialogTitle>
          <DialogDescription>
            Upload a CSV file with columns: <code>unit_id, account_number, amount, fee_type</code>.
          </DialogDescription>
        </DialogHeader>

        {!file ? (
          <div 
            {...getRootProps()} 
            className={`border-2 border-dashed rounded-lg p-10 text-center cursor-pointer transition-colors
              ${isDragActive ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted'}`}
          >
            <input {...getInputProps()} />
            <Upload className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
            <p className="text-sm font-medium">
              Drag & drop CSV file here, or click to select
            </p>
            <p className="text-xs text-muted-foreground mt-2">
              Valid fee types: Assessments, Late Fees, Interest, Legal Fees, Admin Fees
            </p>
          </div>
        ) : (
          <div className="flex flex-col gap-4 flex-1 min-h-0">
             <div className="flex items-center justify-between bg-muted p-3 rounded-md border">
                <div className="flex items-center gap-3">
                   <FileText className="w-8 h-8 text-primary" />
                   <div>
                      <p className="text-sm font-medium truncate max-w-[200px]">{file.name}</p>
                      <p className="text-xs text-muted-foreground">{(file.size / 1024).toFixed(1)} KB</p>
                   </div>
                </div>
                <Button variant="ghost" size="sm" onClick={() => { setFile(null); setValidationResult(null); }}>Change</Button>
             </div>

             {analyzing && (
                <div className="py-8 text-center text-muted-foreground">
                    <Loader2 className="w-6 h-6 animate-spin mx-auto mb-2" />
                    Validating file...
                </div>
             )}

             {!analyzing && validationResult && (
                <div className="flex-1 min-h-0 flex flex-col gap-4">
                    {validationResult.valid ? (
                       <Alert className="bg-emerald-50 border-emerald-200">
                          <CheckCircle className="h-4 w-4 text-emerald-600" />
                          <AlertTitle className="text-emerald-800">Validation Successful</AlertTitle>
                          <AlertDescription className="text-emerald-700">
                             Ready to import {validationResult.totalRows} records.
                          </AlertDescription>
                       </Alert>
                    ) : (
                       <Alert variant="destructive">
                          <XCircle className="h-4 w-4" />
                          <AlertTitle>Validation Errors</AlertTitle>
                          <AlertDescription>
                             Found {validationResult.errors?.length || 1} issues in the file.
                          </AlertDescription>
                       </Alert>
                    )}

                    {validationResult.errors && validationResult.errors.length > 0 && (
                        <div className="flex-1 border rounded-md overflow-hidden flex flex-col">
                            <div className="bg-muted px-4 py-2 text-xs font-semibold text-muted-foreground border-b">
                                Error Log
                            </div>
                            <ScrollArea className="flex-1 p-4">
                                <ul className="space-y-2 text-sm text-destructive">
                                    {validationResult.errors.map((err, i) => (
                                        <li key={i} className="flex items-start gap-2">
                                            <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
                                            <span>{err}</span>
                                        </li>
                                    ))}
                                </ul>
                            </ScrollArea>
                        </div>
                    )}
                </div>
             )}
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button 
            onClick={handleImport} 
            disabled={!file || analyzing || uploading || (validationResult && !validationResult.valid)}
          >
            {uploading ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Importing...</> : 'Import Records'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
