import React, { useState, useRef } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, UploadCloud, AlertCircle } from 'lucide-react';
import Papa from 'papaparse';

export default function BudgetCSVImportDialog({ open, onOpenChange, onSuccess }) {
  const { toast } = useToast();
  const fileInputRef = useRef(null);
  
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState(null);
  const [associations, setAssociations] = useState([]);
  const [associationId, setAssociationId] = useState('global');

  React.useEffect(() => {
    if (open) {
      fetchAssociations();
      setFile(null);
      setAssociationId('global');
    }
  }, [open]);

  const fetchAssociations = async () => {
    try {
      const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
      setAssociations(data || []);
    } catch (err) {
      console.error(err);
    }
  };

  const handleFileChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setFile(e.target.files[0]);
    }
  };

  const processImport = async () => {
    if (!file) {
      toast({ variant: 'destructive', title: 'Error', description: 'Please select a CSV file first.' });
      return;
    }

    setLoading(true);

    Papa.parse(file, {
      header: true,
      skipEmptyLines: true,
      complete: async (results) => {
        try {
          const rows = results.data;
          if (!rows || rows.length === 0) {
            throw new Error('CSV file is empty or invalid.');
          }

          toast({ title: 'Import Started', description: `Processing ${rows.length} lines.` });
          
          if (onSuccess) onSuccess();
          onOpenChange(false);
        } catch (err) {
          console.error(err);
          toast({ variant: 'destructive', title: 'Import Failed', description: err.message });
        } finally {
          setLoading(false);
        }
      },
      error: (error) => {
        console.error('CSV Parse Error:', error);
        toast({ variant: 'destructive', title: 'Parse Error', description: 'Could not parse the CSV file.' });
        setLoading(false);
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UploadCloud className="w-5 h-5 text-primary" />
            Import Budget (CSV)
          </DialogTitle>
          <DialogDescription>
            Upload a CSV file containing budget data. Make sure it includes account numbers and amounts.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <label className="text-sm font-medium">Target Association</label>
            <Select value={associationId} onValueChange={setAssociationId}>
              <SelectTrigger>
                <SelectValue placeholder="Select Association" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="global">Global (All Associations)</SelectItem>
                {associations.filter(c => c && c.id).map(c => (
                  <SelectItem key={c.id} value={String(c.id)}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="grid gap-2">
            <label className="text-sm font-medium">CSV File</label>
            <div 
              className="border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center text-center hover:bg-muted/50 transition-colors cursor-pointer"
              onClick={() => fileInputRef.current?.click()}
            >
              <UploadCloud className="w-8 h-8 text-muted-foreground mb-2" />
              {file ? (
                <span className="text-sm font-medium">{file.name}</span>
              ) : (
                <>
                  <span className="text-sm font-medium">Click to browse</span>
                  <span className="text-xs text-muted-foreground mt-1">Supports .csv files</span>
                </>
              )}
              <input 
                type="file" 
                accept=".csv" 
                className="hidden" 
                ref={fileInputRef}
                onChange={handleFileChange}
              />
            </div>
          </div>

          <div className="bg-blue-50 text-blue-800 p-3 rounded-md flex gap-2 text-sm">
            <AlertCircle className="w-5 h-5 shrink-0" />
            <p>Ensure columns include <strong>Account Number</strong> and <strong>Annual Amount</strong>.</p>
          </div>
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
            Cancel
          </Button>
          <Button type="button" onClick={processImport} disabled={loading || !file}>
            {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
            Import Data
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
