'use client';

import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  Upload, Download, FileText, Trash2, Loader2, CheckCircle2, XCircle,
  AlertTriangle, Paperclip, FileUp, Sparkles, Edit3, ArrowLeft, ArrowRight,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { authFetch, getAuthHeaders } from '@/lib/api';

interface ParsedRow {
  clientName: string;
  clientPhone: string;
  clientEmail: string;
  complaintType: string;
  priority: string;
  description: string;
  areaCode: string;
  clientAddress?: string;
  _sourceFile?: string;
  _isFileAttachment?: boolean;
  _fileName?: string;
  _extractionError?: string;
  _extractionMethod?: 'csv' | 'ai';
}

interface ImportSummary {
  total: number;
  success: number;
  failed: number;
  errors: string[];
}

interface ExtractionProgress {
  fileName: string;
  status: 'pending' | 'extracting' | 'done' | 'error';
  error?: string;
}

export default function BulkUpload() {
  const { t } = useTranslation();
  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [areas, setAreas] = useState<Array<{ id: string; name: string; code: string }>>([]);
  const [selectedAreaId, setSelectedAreaId] = useState('');
  const [files, setFiles] = useState<File[]>([]);
  const [parsedData, setParsedData] = useState<ParsedRow[]>([]);
  const [isDragOver, setIsDragOver] = useState(false);
  const [importing, setImporting] = useState(false);
  const [progress, setProgress] = useState(0);
  const [summary, setSummary] = useState<ImportSummary | null>(null);
  const [step, setStep] = useState<'upload' | 'extracting' | 'preview' | 'importing' | 'done'>('upload');
  const [extractionProgress, setExtractionProgress] = useState<ExtractionProgress[]>([]);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingRow, setEditingRow] = useState<{ index: number; data: ParsedRow } | null>(null);

  useEffect(() => {
    const fetchAreas = async () => {
      try {
        const res = await authFetch('/api/areas');
        if (res.ok) {
          const data = await res.json();
          setAreas(data.areas || []);
          if (data.areas?.length > 0 && !selectedAreaId) {
            setSelectedAreaId(data.areas[0].id);
          }
        }
      } catch (err) {
        console.error('Fetch areas error:', err);
      }
    };
    fetchAreas();
  }, []);

  const handleFileSelect = (newFiles: FileList | null) => {
    if (!newFiles) return;
    const allowed = ['.pdf', '.xlsx', '.xls', '.csv', '.png', '.jpg', '.jpeg', '.doc', '.docx'];
    const fileArray = Array.from(newFiles).filter(f => {
      const ext = '.' + f.name.split('.').pop()?.toLowerCase();
      return allowed.includes(ext);
    });
    setFiles(prev => [...prev, ...fileArray]);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const removeFile = (index: number) => {
    const updated = [...files];
    updated.splice(index, 1);
    setFiles(updated);
  };

  /* ---------- Client-side CSV Parsing ---------- */
  const parseCSV = (text: string, fileName: string): ParsedRow[] => {
    const lines = text.split(/\r?\n/).filter(line => line.trim());
    if (lines.length < 2) return [];

    const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));
    const rows: ParsedRow[] = [];

    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',').map(v => v.trim().replace(/^"|"$/g, ''));
      if (values.length < 3) continue;

      const row: Record<string, string> = {};
      headers.forEach((h, idx) => {
        row[h] = values[idx] || '';
      });

      rows.push({
        clientName: row.clientName || row['Client Name'] || '',
        clientPhone: row.clientPhone || row['Client Phone'] || row.phone || '',
        clientEmail: row.clientEmail || row['Client Email'] || row.email || '',
        complaintType: row.complaintType || row['Complaint Type'] || row.type || 'other',
        priority: row.priority || row.Priority || 'medium',
        description: row.description || row.Description || '',
        areaCode: row.areaCode || row['Area Code'] || row.areaCode || '',
        _sourceFile: fileName,
        _extractionMethod: 'csv',
      });
    }
    return rows;
  };

  /* ---------- Process all uploaded files ---------- */
  const processFiles = async () => {
    if (files.length === 0) return;
    const allParsedData: ParsedRow[] = [];
    const csvFiles: File[] = [];
    const nonCsvFiles: File[] = [];

    // Separate CSV files from non-CSV files
    for (const file of files) {
      const ext = file.name.split('.').pop()?.toLowerCase() || '';
      if (ext === 'csv') {
        csvFiles.push(file);
      } else {
        nonCsvFiles.push(file);
      }
    }

    // Process CSV files directly
    for (const file of csvFiles) {
      const text = await file.text();
      const csvRows = parseCSV(text, file.name);
      allParsedData.push(...csvRows);
    }

    // If there are non-CSV files, we need AI extraction
    if (nonCsvFiles.length > 0) {
      setStep('extracting');
      const progressItems: ExtractionProgress[] = nonCsvFiles.map(f => ({
        fileName: f.name,
        status: 'pending' as const,
      }));
      setExtractionProgress(progressItems);

      try {
        // Convert files to base64
        const filesForApi: Array<{ name: string; data: string; type: string }> = [];

        for (let i = 0; i < nonCsvFiles.length; i++) {
          const file = nonCsvFiles[i];
          setExtractionProgress(prev =>
            prev.map((p, idx) => idx === i ? { ...p, status: 'extracting' as const } : p)
          );

          const arrayBuffer = await file.arrayBuffer();
          // Chunked base64 encoding to handle large files
          const bytes = new Uint8Array(arrayBuffer);
          const chunks: string[] = [];
          for (let j = 0; j < bytes.length; j += 8192) {
            chunks.push(String.fromCharCode(...bytes.subarray(j, j + 8192)));
          }
          const base64 = btoa(chunks.join(''));
          filesForApi.push({
            name: file.name,
            data: base64,
            type: file.type || 'application/octet-stream',
          });
        }

        // Call the AI extraction API
        const res = await authFetch('/api/ai-extract', {
          method: 'POST',
          body: JSON.stringify({ files: filesForApi }),
        });

        if (res.ok) {
          const data = await res.json();
          const extracted: Array<ParsedRow & { _extractionError?: string }> = data.extracted || [];

          for (let i = 0; i < nonCsvFiles.length; i++) {
            const extractedItem = extracted[i];
            if (extractedItem) {
              allParsedData.push({
                clientName: extractedItem.clientName || '',
                clientPhone: extractedItem.clientPhone || '',
                clientEmail: extractedItem.clientEmail || '',
                clientAddress: extractedItem.clientAddress || '',
                complaintType: extractedItem.complaintType || 'other',
                priority: extractedItem.priority || 'medium',
                description: extractedItem.description || `Complaint from file: ${nonCsvFiles[i].name}`,
                areaCode: '',
                _sourceFile: nonCsvFiles[i].name,
                _isFileAttachment: true,
                _fileName: nonCsvFiles[i].name,
                _extractionError: extractedItem._extractionError,
                _extractionMethod: 'ai',
              });

              setExtractionProgress(prev =>
                prev.map((p, idx) =>
                  idx === i
                    ? {
                        ...p,
                        status: extractedItem._extractionError ? 'error' as const : 'done' as const,
                        error: extractedItem._extractionError,
                      }
                    : p
                )
              );
            } else {
              allParsedData.push({
                clientName: '',
                clientPhone: '',
                clientEmail: '',
                complaintType: 'other',
                priority: 'medium',
                description: `Complaint from file: ${nonCsvFiles[i].name}`,
                areaCode: '',
                _sourceFile: nonCsvFiles[i].name,
                _isFileAttachment: true,
                _fileName: nonCsvFiles[i].name,
                _extractionError: 'No data extracted',
                _extractionMethod: 'ai',
              });

              setExtractionProgress(prev =>
                prev.map((p, idx) =>
                  idx === i ? { ...p, status: 'error' as const, error: 'No data extracted' } : p
                )
              );
            }
          }

          toast({
            title: 'AI Extraction Complete',
            description: `${nonCsvFiles.length} file(s) processed with AI`,
          });
        } else {
          // API failed, create placeholder entries
          for (const file of nonCsvFiles) {
            allParsedData.push({
              clientName: 'AI Extraction Failed',
              clientPhone: 'N/A',
              clientEmail: '',
              complaintType: 'other',
              priority: 'medium',
              description: `Complaint from file: ${file.name} (AI extraction failed - please edit manually)`,
              areaCode: '',
              _sourceFile: file.name,
              _isFileAttachment: true,
              _fileName: file.name,
              _extractionError: 'AI extraction API failed',
              _extractionMethod: 'ai',
            });
          }

          setExtractionProgress(prev =>
            prev.map(p => ({ ...p, status: 'error' as const, error: 'API request failed' }))
          );

          toast({
            title: 'AI Extraction Failed',
            description: 'Could not extract data from non-CSV files. Placeholder entries created.',
            variant: 'destructive',
          });
        }
      } catch (err) {
        console.error('AI extraction error:', err);
        for (const file of nonCsvFiles) {
          allParsedData.push({
            clientName: '',
            clientPhone: '',
            clientEmail: '',
            complaintType: 'other',
            priority: 'medium',
            description: `Complaint from file: ${file.name}`,
            areaCode: '',
            _sourceFile: file.name,
            _isFileAttachment: true,
            _fileName: file.name,
            _extractionError: 'Network error during extraction',
            _extractionMethod: 'ai',
          });
        }

        setExtractionProgress(prev =>
          prev.map(p => ({ ...p, status: 'error' as const, error: 'Network error' }))
        );
      }

      // Brief pause to show results
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    setParsedData(allParsedData);
    setStep('preview');
  };

  /* ---------- Import all parsed data ---------- */
  const confirmImport = async () => {
    if (parsedData.length === 0) return;
    setImporting(true);
    setStep('importing');
    setProgress(0);

    const importSummary: ImportSummary = { total: parsedData.length, success: 0, failed: 0, errors: [] };

    for (let i = 0; i < parsedData.length; i++) {
      const row = parsedData[i];
      try {
        let areaId = selectedAreaId;
        if (row.areaCode) {
          const areaByCode = areas.find(a => a.code.toLowerCase() === row.areaCode.toLowerCase());
          if (areaByCode) areaId = areaByCode.id;
        }

        const res = await authFetch('/api/complaints', {
          method: 'POST',
          body: JSON.stringify({
            clientName: row.clientName || 'Unknown',
            clientPhone: row.clientPhone || 'N/A',
            clientEmail: row.clientEmail || undefined,
            clientAddress: row.clientAddress || undefined,
            complaintType: row.complaintType || 'other',
            priority: row.priority || 'medium',
            description: row.description || 'No description',
            areaId,
            source: 'bulk_upload',
            attachments: row._fileName ? [row._fileName] : undefined,
          }),
        });

        if (res.ok) {
          importSummary.success++;
        } else {
          importSummary.failed++;
          const data = await res.json();
          importSummary.errors.push(`Row ${i + 1}: ${data.error || 'Failed'}`);
        }
      } catch {
        importSummary.failed++;
        importSummary.errors.push(`Row ${i + 1}: Network error`);
      }

      setProgress(Math.round(((i + 1) / parsedData.length) * 100));
    }

    setSummary(importSummary);
    setStep('done');
    setImporting(false);

    toast({
      title: 'Import Complete',
      description: `${importSummary.success} succeeded, ${importSummary.failed} failed`,
      variant: importSummary.failed > 0 ? 'destructive' : 'default',
    });
  };

  /* ---------- Download sample CSV ---------- */
  const downloadSampleCSV = () => {
    const headers = 'clientName,clientPhone,clientEmail,complaintType,priority,description,areaCode';
    const rows = [
      'John Doe,+880171234567,john@example.com,hardware,high,Printer not working in office,AREA01',
      'Jane Smith,+880189876543,jane@example.com,software,medium,Email client crashing on startup,AREA02',
      'Bob Wilson,+880155544433,bob@example.com,network,low,WiFi signal weak in conference room,AREA03',
    ];
    const csvContent = [headers, ...rows].join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'sample_complaints.csv';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const resetUpload = () => {
    setFiles([]);
    setParsedData([]);
    setSummary(null);
    setStep('upload');
    setProgress(0);
    setExtractionProgress([]);
  };

  const priorityColor = (p: string) => {
    const m: Record<string, string> = {
      low: 'bg-gray-100 text-gray-800 dark:bg-gray-950/30 dark:text-gray-300',
      medium: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-950/30 dark:text-yellow-300',
      high: 'bg-orange-100 text-orange-800 dark:bg-orange-950/30 dark:text-orange-300',
      critical: 'bg-red-100 text-red-800 dark:bg-red-950/30 dark:text-red-300',
    };
    return m[p] || '';
  };

  /* ---------- Edit row ---------- */
  const openEditRow = (index: number) => {
    setEditingRow({ index, data: { ...parsedData[index] } });
    setEditDialogOpen(true);
  };

  const saveEditRow = () => {
    if (!editingRow) return;
    const updated = [...parsedData];
    updated[editingRow.index] = editingRow.data;
    setParsedData(updated);
    setEditDialogOpen(false);
    setEditingRow(null);
  };

  const removeParsedRow = (index: number) => {
    const updated = [...parsedData];
    updated.splice(index, 1);
    setParsedData(updated);
  };

  // Count CSV vs non-CSV files
  const csvFilesCount = files.filter(f => f.name.split('.').pop()?.toLowerCase() === 'csv').length;
  const nonCsvFilesCount = files.length - csvFilesCount;

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Bulk Upload</h1>
          <p className="text-sm text-muted-foreground mt-1">Import complaints from CSV, Excel, PDF, Word, or image files</p>
        </div>
        <Button variant="outline" onClick={downloadSampleCSV} className="border-emerald-200 text-emerald-700 hover:bg-emerald-50">
          <Download className="w-4 h-4 mr-2" /> Download Sample CSV
        </Button>
      </div>

      {/* Step: Upload */}
      {step === 'upload' && (
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">Upload Files</CardTitle>
              <CardDescription>
                Upload CSV, Excel, PDF, Word, or image files. CSV files will be parsed directly. Other files will use AI extraction to pull complaint data.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Default Area Selection */}
              <div className="space-y-1.5">
                <Label className="text-xs font-medium">Default Area for Import</Label>
                <Select value={selectedAreaId} onValueChange={setSelectedAreaId}>
                  <SelectTrigger className="w-64">
                    <SelectValue placeholder="Select default area" />
                  </SelectTrigger>
                  <SelectContent>
                    {areas.map((a) => (
                      <SelectItem key={a.id} value={a.id}>{a.name} ({a.code})</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Drop Zone */}
              <div
                className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer ${
                  isDragOver
                    ? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-950/20'
                    : 'border-emerald-300 dark:border-emerald-700 hover:border-emerald-500'
                }`}
                onDragOver={(e) => { e.preventDefault(); setIsDragOver(true); }}
                onDragLeave={(e) => { e.preventDefault(); setIsDragOver(false); }}
                onDrop={(e) => { e.preventDefault(); setIsDragOver(false); handleFileSelect(e.dataTransfer.files); }}
                onClick={() => fileInputRef.current?.click()}
              >
                <FileUp className="w-10 h-10 text-emerald-500 mx-auto mb-2" />
                <p className="text-sm font-medium">Drag & drop files here or click to browse</p>
                <p className="text-xs text-muted-foreground mt-1">Supports: CSV, XLSX, XLS, PDF, DOC, DOCX, JPG, PNG</p>
                <input
                  ref={fileInputRef}
                  type="file"
                  multiple
                  className="hidden"
                  accept=".pdf,.xlsx,.xls,.csv,.png,.jpg,.jpeg,.doc,.docx"
                  onChange={(e) => handleFileSelect(e.target.files)}
                />
              </div>

              {/* File List */}
              {files.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">{files.length} file(s) selected</span>
                    <Button variant="ghost" size="sm" onClick={() => setFiles([])} className="text-red-500 hover:text-red-600">
                      Clear All
                    </Button>
                  </div>
                  <div className="space-y-1.5 max-h-48 overflow-y-auto">
                    {files.map((f, idx) => {
                      const ext = f.name.split('.').pop()?.toLowerCase() || '';
                      const isCsv = ext === 'csv';
                      return (
                        <div key={`${f.name}-${idx}`} className="flex items-center gap-2 bg-muted/50 rounded-md px-3 py-2 text-xs">
                          <FileText className={`w-4 h-4 ${isCsv ? 'text-emerald-500' : 'text-purple-500'} flex-shrink-0`} />
                          <span className="truncate flex-1 font-medium">{f.name}</span>
                          <Badge variant={isCsv ? 'secondary' : 'outline'} className="text-[10px] flex-shrink-0">
                            {isCsv ? 'CSV Parse' : 'AI Extract'}
                          </Badge>
                          <Badge variant="outline" className="text-[10px] flex-shrink-0">
                            {(f.size / 1024).toFixed(1)} KB
                          </Badge>
                          <Button variant="ghost" size="icon" className="h-5 w-5" onClick={() => removeFile(idx)}>
                            <Trash2 className="w-3 h-3 text-red-500" />
                          </Button>
                        </div>
                      );
                    })}
                  </div>

                  {/* File type summary */}
                  <div className="flex gap-3 text-xs text-muted-foreground">
                    {csvFilesCount > 0 && (
                      <span className="flex items-center gap-1">
                        <FileText className="w-3 h-3 text-emerald-500" />
                        {csvFilesCount} CSV (direct parse)
                      </span>
                    )}
                    {nonCsvFilesCount > 0 && (
                      <span className="flex items-center gap-1">
                        <Sparkles className="w-3 h-3 text-purple-500" />
                        {nonCsvFilesCount} file(s) (AI extraction)
                      </span>
                    )}
                  </div>

                  <Button onClick={processFiles} className="bg-emerald-600 hover:bg-emerald-700">
                    {nonCsvFilesCount > 0 ? (
                      <>
                        <Sparkles className="w-4 h-4 mr-2" /> Parse & AI Extract
                      </>
                    ) : (
                      <>
                        <Upload className="w-4 h-4 mr-2" /> Parse & Preview
                      </>
                    )}
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      )}

      {/* Step: AI Extraction Progress */}
      {step === 'extracting' && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Sparkles className="w-5 h-5 text-purple-500" />
              AI Data Extraction
            </CardTitle>
            <CardDescription>Extracting complaint data from uploaded files using AI...</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {extractionProgress.map((item, idx) => (
              <div key={idx} className="flex items-center gap-3 bg-muted/50 rounded-md px-3 py-2.5">
                {item.status === 'pending' && (
                  <div className="w-5 h-5 rounded-full bg-gray-200 dark:bg-gray-700 flex-shrink-0" />
                )}
                {item.status === 'extracting' && (
                  <Loader2 className="w-5 h-5 animate-spin text-purple-500 flex-shrink-0" />
                )}
                {item.status === 'done' && (
                  <CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />
                )}
                {item.status === 'error' && (
                  <AlertTriangle className="w-5 h-5 text-orange-500 flex-shrink-0" />
                )}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">{item.fileName}</p>
                  <p className="text-xs text-muted-foreground">
                    {item.status === 'pending' && 'Waiting...'}
                    {item.status === 'extracting' && 'Extracting data with AI...'}
                    {item.status === 'done' && 'Data extracted successfully'}
                    {item.status === 'error' && (item.error || 'Extraction failed')}
                  </p>
                </div>
              </div>
            ))}
            <div className="text-center py-2">
              <Loader2 className="w-6 h-6 animate-spin text-emerald-600 mx-auto mb-2" />
              <p className="text-xs text-muted-foreground">AI extraction in progress. This may take a moment...</p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Step: Preview */}
      {step === 'preview' && (
        <div className="space-y-4">
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-base">Preview Extracted Data</CardTitle>
                  <CardDescription>{parsedData.length} complaint(s) will be imported. Click any cell to edit.</CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" onClick={resetUpload} size="sm">
                    <ArrowLeft className="w-4 h-4 mr-1" /> Back
                  </Button>
                  <Button onClick={confirmImport} className="bg-emerald-600 hover:bg-emerald-700" size="sm">
                    <Upload className="w-4 h-4 mr-1" /> Import {parsedData.length} Complaints
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-xs">#</TableHead>
                      <TableHead className="text-xs">Client Name</TableHead>
                      <TableHead className="text-xs">Phone</TableHead>
                      <TableHead className="text-xs">Email</TableHead>
                      <TableHead className="text-xs">Type</TableHead>
                      <TableHead className="text-xs">Priority</TableHead>
                      <TableHead className="text-xs">Description</TableHead>
                      <TableHead className="text-xs">Source</TableHead>
                      <TableHead className="text-xs">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {parsedData.map((row, idx) => (
                      <TableRow key={idx} className={row._extractionError ? 'bg-orange-50/50 dark:bg-orange-950/10' : ''}>
                        <TableCell className="text-xs">{idx + 1}</TableCell>
                        <TableCell className="text-xs font-medium">{row.clientName || '-'}</TableCell>
                        <TableCell className="text-xs">{row.clientPhone || '-'}</TableCell>
                        <TableCell className="text-xs">{row.clientEmail || '-'}</TableCell>
                        <TableCell className="text-xs capitalize">{row.complaintType}</TableCell>
                        <TableCell>
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium ${priorityColor(row.priority)}`}>
                            {row.priority}
                          </span>
                        </TableCell>
                        <TableCell className="text-xs max-w-[200px] truncate">{row.description}</TableCell>
                        <TableCell className="text-xs">
                          <div className="flex items-center gap-1">
                            {row._extractionMethod === 'ai' ? (
                              <Badge variant="outline" className="text-[10px] border-purple-300 text-purple-700">
                                <Sparkles className="w-2.5 h-2.5 mr-0.5" /> AI
                              </Badge>
                            ) : (
                              <Badge variant="outline" className="text-[10px]">
                                <FileText className="w-2.5 h-2.5 mr-0.5" /> CSV
                              </Badge>
                            )}
                            {row._extractionError && (
                              <Badge variant="outline" className="text-[10px] border-orange-300 text-orange-700">
                                <AlertTriangle className="w-2.5 h-2.5 mr-0.5" />
                              </Badge>
                            )}
                          </div>
                          {row._isFileAttachment && (
                            <span className="text-[10px] text-muted-foreground block mt-0.5 truncate max-w-[120px]">
                              {row._sourceFile}
                            </span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => openEditRow(idx)}
                            >
                              <Edit3 className="w-3 h-3" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => removeParsedRow(idx)}
                            >
                              <Trash2 className="w-3 h-3 text-red-500" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Step: Importing */}
      {step === 'importing' && (
        <Card>
          <CardContent className="p-8 text-center">
            <Loader2 className="w-10 h-10 animate-spin text-emerald-600 mx-auto mb-4" />
            <p className="text-sm font-medium">Importing complaints...</p>
            <p className="text-xs text-muted-foreground mt-1">{progress}% complete</p>
            <Progress value={progress} className="mt-4 max-w-md mx-auto" />
          </CardContent>
        </Card>
      )}

      {/* Step: Done */}
      {step === 'done' && summary && (
        <div className="space-y-4">
          <Card className={summary.failed === 0 ? 'border-emerald-300' : 'border-orange-300'}>
            <CardContent className="p-6">
              <div className="text-center">
                {summary.failed === 0 ? (
                  <CheckCircle2 className="w-12 h-12 text-emerald-600 mx-auto mb-3" />
                ) : (
                  <AlertTriangle className="w-12 h-12 text-orange-500 mx-auto mb-3" />
                )}
                <h2 className="text-lg font-bold">Import Complete</h2>
                <p className="text-sm text-muted-foreground mt-1">
                  {summary.success} of {summary.total} complaints imported successfully
                </p>
                <div className="flex justify-center gap-6 mt-4">
                  <div className="text-center">
                    <p className="text-2xl font-bold text-emerald-600">{summary.success}</p>
                    <p className="text-xs text-muted-foreground">Succeeded</p>
                  </div>
                  <div className="text-center">
                    <p className="text-2xl font-bold text-red-500">{summary.failed}</p>
                    <p className="text-xs text-muted-foreground">Failed</p>
                  </div>
                </div>
              </div>

              {summary.errors.length > 0 && (
                <div className="mt-4 text-left">
                  <p className="text-xs font-medium text-red-600 mb-1">Errors:</p>
                  <div className="max-h-32 overflow-y-auto space-y-0.5">
                    {summary.errors.map((err, idx) => (
                      <p key={idx} className="text-xs text-red-500">{err}</p>
                    ))}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          <div className="flex gap-3">
            <Button onClick={resetUpload} className="bg-emerald-600 hover:bg-emerald-700">
              <Upload className="w-4 h-4 mr-2" /> Upload More
            </Button>
          </div>
        </div>
      )}

      {/* Edit Row Dialog */}
      <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Edit Extracted Data</DialogTitle>
            <DialogDescription>Modify the extracted complaint information before importing</DialogDescription>
          </DialogHeader>
          {editingRow && (
            <div className="space-y-3 py-2">
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs">Client Name</Label>
                  <Input
                    value={editingRow.data.clientName}
                    onChange={(e) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, clientName: e.target.value } } : prev)}
                    className="h-9"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Phone</Label>
                  <Input
                    value={editingRow.data.clientPhone}
                    onChange={(e) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, clientPhone: e.target.value } } : prev)}
                    className="h-9"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs">Email</Label>
                  <Input
                    value={editingRow.data.clientEmail}
                    onChange={(e) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, clientEmail: e.target.value } } : prev)}
                    className="h-9"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Address</Label>
                  <Input
                    value={editingRow.data.clientAddress || ''}
                    onChange={(e) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, clientAddress: e.target.value } } : prev)}
                    className="h-9"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1.5">
                  <Label className="text-xs">Complaint Type</Label>
                  <Select
                    value={editingRow.data.complaintType}
                    onValueChange={(v) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, complaintType: v } } : prev)}
                  >
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="hardware">Hardware</SelectItem>
                      <SelectItem value="software">Software</SelectItem>
                      <SelectItem value="network">Network</SelectItem>
                      <SelectItem value="other">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Priority</Label>
                  <Select
                    value={editingRow.data.priority}
                    onValueChange={(v) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, priority: v } } : prev)}
                  >
                    <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="low">Low</SelectItem>
                      <SelectItem value="medium">Medium</SelectItem>
                      <SelectItem value="high">High</SelectItem>
                      <SelectItem value="critical">Critical</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Description</Label>
                <Textarea
                  value={editingRow.data.description}
                  onChange={(e) => setEditingRow(prev => prev ? { ...prev, data: { ...prev.data, description: e.target.value } } : prev)}
                  rows={3}
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditDialogOpen(false)}>Cancel</Button>
            <Button onClick={saveEditRow} className="bg-emerald-600 hover:bg-emerald-700">Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
