import React, { useState, useRef } from 'react';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogDescription, 
  DialogFooter 
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { AlertCircle, Loader2 } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import Papa from 'papaparse';

const LOG_PREFIX = '[ChecklistImportDialog]';

// Simple built-in parsers instead of external service dependency
const parseJSON = async (file) => {
  const text = await file.text();
  const data = JSON.parse(text);
  const items = Array.isArray(data) ? data : [data];
  const headers = items.length > 0 ? Object.keys(items[0]) : [];
  return { items, headers };
};

const parseCSV = async (file) => {
  return new Promise((resolve, reject) => {
    Papa.parse(file, {
      header: true,
      skipEmptyLines: true,
      complete: (results) => {
        resolve({ items: results.data, headers: results.meta.fields || [] });
      },
      error: (err) => reject(err),
    });
  });
};

const parseText = async (file) => {
  const text = await file.text();
  const lines = text.split('\n').filter(l => l.trim());
  const items = lines.map((line, i) => ({ item: line.trim(), index: i + 1 }));
  return { items, headers: ['item', 'index'] };
};

export default function ChecklistImportDialog({ open, onOpenChange, onNext }) {
  const [file, setFile] = useState(null);
  const [items, setItems] = useState([]);
  const [headers, setHeaders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const fileInputRef = useRef(null);
  const { toast } = useToast();

  const handleFileChange = async (e) => {
    const selectedFile = e.target.files?.[0];
    if (!selectedFile) return;

    setFile(selectedFile);
    setLoading(true);
    setError(null);
    setItems([]);
    setHeaders([]);

    console.log(`${LOG_PREFIX} File selected`, selectedFile.name);

    try {
      let result = { items: [], headers: [] };
      const type = selectedFile.type;
      const name = selectedFile.name.toLowerCase();

      if (name.endsWith('.json') || type === 'application/json') {
        result = await parseJSON(selectedFile);
      } else if (name.endsWith('.csv') || type === 'text/csv') {
        result = await parseCSV(selectedFile);
      } else if (name.endsWith('.txt') || type === 'text/plain') {
        result = await parseText(selectedFile);
      } else {
        throw new Error("Unsupported file format. Please use JSON, CSV, or TXT.");
      }

      console.log(`${LOG_PREFIX} Parse Result`, result);

      if (result.items.length === 0) {
        throw new Error("No valid items found in file.");
      }

      setItems(result.items);
      setHeaders(result.headers);
    } catch (err) {
      console.error(`${LOG_PREFIX} Error`, err);
      setError(err.message);
      setFile(null);
      if (fileInputRef.current) fileInputRef.current.value = '';
    } finally {
      setLoading(false);
    }
  };

  const handleNext = () => {
    if (items.length === 0) return;
    console.log(`${LOG_PREFIX} Proceeding with`, { itemCount: items.length, headers });
    
    if (onNext) {
      onNext(items, headers, file?.name?.split('.')[0] || "Imported Checklist");
    }
    
    setFile(null);
    setItems([]);
    setHeaders([]);
    setError(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Import Checklist</DialogTitle>
          <DialogDescription>
            Upload a file (CSV, JSON, TXT) to import checklist items. First row/key will be used as headers.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="grid w-full max-w-sm items-center gap-1.5">
            <Label htmlFor="checklist-file">Checklist File</Label>
            <Input 
              ref={fileInputRef}
              id="checklist-file" 
              type="file" 
              accept=".json,.csv,.txt"
              onChange={handleFileChange}
              className="cursor-pointer"
            />
          </div>

          {loading && (
            <div className="flex items-center justify-center py-8 text-slate-500">
              <Loader2 className="w-6 h-6 animate-spin mr-3" />
              Parsing file contents...
            </div>
          )}

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {items.length > 0 && !loading && (
            <div className="space-y-3">
               <div className="flex items-center justify-between">
                 <Label>Preview ({items.length} items)</Label>
                 <Button variant="ghost" size="sm" onClick={() => {
                   setFile(null);
                   setItems([]);
                   setHeaders([]);
                   if(fileInputRef.current) fileInputRef.current.value = '';
                 }}>Clear</Button>
               </div>
               
               <div className="border rounded-md">
                 <ScrollArea className="h-[250px] w-full bg-slate-50/50">
                    <Table>
                      <TableHeader className="bg-slate-100 sticky top-0">
                        <TableRow>
                          {headers.map((h, i) => (
                            <TableHead key={i} className="text-xs font-semibold">{h}</TableHead>
                          ))}
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {items.slice(0, 10).map((item, idx) => (
                          <TableRow key={idx} className="text-xs">
                            {headers.map((h, i) => (
                              <TableCell key={i} className="py-2">{item[h] || '-'}</TableCell>
                            ))}
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                 </ScrollArea>
                 {items.length > 10 && (
                   <div className="p-2 text-center text-xs text-slate-400 border-t bg-slate-50">
                     And {items.length - 10} more items...
                   </div>
                 )}
               </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleNext} disabled={items.length === 0 || loading}>
            Next
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}