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 { Loader2, Upload, FileText, CheckCircle, AlertTriangle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

export function IcsImportDialog({ open, onOpenChange, onImport }) {
  const [file, setFile] = useState(null);
  const [parsedEvents, setParsedEvents] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const onDrop = useCallback((acceptedFiles) => {
    const uploadedFile = acceptedFiles[0];
    if (uploadedFile) {
        setFile(uploadedFile);
        parseIcs(uploadedFile);
    }
  }, []);

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

  const parseIcs = async (file) => {
    const reader = new FileReader();
    reader.onload = async () => {
        try {
            // Dynamic import for ical.js
            const ICAL = (await import('ical.js')).default;
            const jcalData = ICAL.parse(reader.result);
            const comp = new ICAL.Component(jcalData);
            const vevents = comp.getAllSubcomponents('vevent');
            
            const events = vevents.map(vevent => {
                const event = new ICAL.Event(vevent);
                return {
                    title: event.summary,
                    description: event.description,
                    start_time: event.startDate.toJSDate().toISOString(),
                    end_time: event.endDate.toJSDate().toISOString(),
                    location: event.location,
                    source: 'ics_import'
                };
            });
            setParsedEvents(events);
        } catch (err) {
            console.error(err);
            toast({ variant: "destructive", title: "Parse Error", description: "Invalid ICS file format." });
            setFile(null);
        }
    };
    reader.readAsText(file);
  };

  const handleImport = async () => {
    setLoading(true);
    try {
        await onImport(parsedEvents);
        toast({ title: "Import Successful", description: `Imported ${parsedEvents.length} events.` });
        onOpenChange(false);
        setFile(null);
        setParsedEvents([]);
    } catch (err) {
        toast({ variant: "destructive", title: "Import Failed", description: err.message });
    } finally {
        setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>Import Calendar (.ics)</DialogTitle>
          <DialogDescription>Import events from external calendar files.</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="w-10 h-10 mx-auto text-muted-foreground mb-4" />
                <p className="text-foreground font-medium">Drag & drop .ics file here, or click to select</p>
                <p className="text-xs text-muted-foreground mt-2">Maximum file size 5MB</p>
            </div>
        ) : (
            <div className="space-y-4">
                <div className="flex items-center justify-between p-3 bg-muted rounded border">
                    <div className="flex items-center gap-3">
                        <FileText className="w-5 h-5 text-primary" />
                        <span className="font-medium text-sm">{file.name}</span>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => { setFile(null); setParsedEvents([]); }}>Change</Button>
                </div>

                <div className="bg-primary/5 border border-primary/20 rounded-md p-3 flex items-start gap-3">
                    <CheckCircle className="w-5 h-5 text-primary mt-0.5" />
                    <div>
                        <p className="text-sm font-medium">Ready to Import</p>
                        <p className="text-xs text-muted-foreground">Found {parsedEvents.length} events in file.</p>
                    </div>
                </div>

                <ScrollArea className="h-40 border rounded p-2">
                    {parsedEvents.map((ev, i) => (
                        <div key={i} className="text-xs py-1 border-b last:border-0">
                            <strong>{ev.title}</strong> - {new Date(ev.start_time).toLocaleDateString()}
                        </div>
                    ))}
                </ScrollArea>
            </div>
        )}

        <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button onClick={handleImport} disabled={!file || parsedEvents.length === 0 || loading}>
                {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                Import Events
            </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
