import { useState, useRef } from 'react';
import { api } from '@/lib/api';
import type { ImportPreview, ImportResult } from '@/types';
import Modal from '@/components/Modal';
import LoadingSpinner from '@/components/LoadingSpinner';
import { Upload, FileSpreadsheet, CheckCircle2, AlertCircle, ArrowRight, X } from 'lucide-react';

const CLIENT_FIELDS = [
  { value: '', label: '-- Skip --' },
  { value: 'firstName', label: 'First Name' },
  { value: 'lastName', label: 'Last Name' },
  { value: 'email', label: 'Email' },
  { value: 'phone', label: 'Phone' },
  { value: 'company', label: 'Company' },
  { value: 'role', label: 'Role/Title' },
  { value: 'industry', label: 'Industry' },
  { value: 'street', label: 'Street' },
  { value: 'city', label: 'City' },
  { value: 'state', label: 'State' },
  { value: 'zip', label: 'ZIP Code' },
  { value: 'birthday', label: 'Birthday' },
  { value: 'anniversary', label: 'Anniversary' },
  { value: 'notes', label: 'Notes' },
  { value: 'tags', label: 'Tags (comma-separated)' },
  { value: 'interests', label: 'Interests (comma-separated)' },
];

interface CSVImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  onComplete: () => void;
}

type Step = 'upload' | 'mapping' | 'importing' | 'results';

export default function CSVImportModal({ isOpen, onClose, onComplete }: CSVImportModalProps) {
  const [step, setStep] = useState<Step>('upload');
  const [file, setFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<ImportPreview | null>(null);
  const [mapping, setMapping] = useState<Record<number, string>>({});
  const [result, setResult] = useState<ImportResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const reset = () => {
    setStep('upload');
    setFile(null);
    setPreview(null);
    setMapping({});
    setResult(null);
    setError(null);
    setLoading(false);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    
    setFile(f);
    setError(null);
    setLoading(true);

    try {
      const previewData = await api.importPreview(f);
      setPreview(previewData);
      setMapping(previewData.mapping);
      setStep('mapping');
    } catch (err: any) {
      setError(err.message || 'Failed to parse CSV');
    } finally {
      setLoading(false);
    }
  };

  const updateMapping = (colIndex: number, field: string) => {
    setMapping(prev => {
      const next = { ...prev };
      if (field === '') {
        delete next[colIndex];
      } else {
        next[colIndex] = field;
      }
      return next;
    });
  };

  const hasRequiredFields = () => {
    const values = Object.values(mapping);
    return values.includes('firstName') && values.includes('lastName');
  };

  const handleImport = async () => {
    if (!file || !hasRequiredFields()) return;
    
    setStep('importing');
    setLoading(true);
    setError(null);

    try {
      const importResult = await api.importClients(file, mapping);
      setResult(importResult);
      setStep('results');
      if (importResult.imported > 0) {
        onComplete();
      }
    } catch (err: any) {
      setError(err.message || 'Import failed');
      setStep('mapping');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={handleClose} title="Import Clients from CSV" size="lg">
      <div className="space-y-5">
        {/* Step: Upload */}
        {step === 'upload' && (
          <div className="space-y-4">
            <div
              onClick={() => fileRef.current?.click()}
              className="border-2 border-dashed border-slate-300 rounded-xl p-8 text-center cursor-pointer hover:border-blue-400 hover:bg-blue-50/50 transition-all"
            >
              <Upload className="w-10 h-10 text-slate-400 mx-auto mb-3" />
              <p className="text-sm font-medium text-slate-700">
                Click to select a CSV file
              </p>
              <p className="text-xs text-slate-400 mt-1">
                Must include at least First Name and Last Name columns
              </p>
            </div>
            <input
              ref={fileRef}
              type="file"
              accept=".csv,text/csv"
              onChange={handleFileSelect}
              className="hidden"
            />
            {loading && (
              <div className="flex items-center justify-center gap-2 py-4">
                <LoadingSpinner size="sm" />
                <span className="text-sm text-slate-500">Parsing CSV...</span>
              </div>
            )}
            {error && (
              <div className="flex items-center gap-2 p-3 bg-red-50 text-red-700 rounded-lg text-sm">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {error}
              </div>
            )}
          </div>
        )}

        {/* Step: Column Mapping */}
        {step === 'mapping' && preview && (
          <div className="space-y-4">
            <div className="flex items-center gap-2 text-sm text-slate-600">
              <FileSpreadsheet className="w-4 h-4" />
              <span><strong>{preview.totalRows}</strong> rows found in <strong>{file?.name}</strong></span>
            </div>

            {/* Column mapping */}
            <div className="space-y-2">
              <h4 className="text-sm font-medium text-slate-700">Map columns to client fields:</h4>
              <div className="max-h-64 overflow-y-auto space-y-2">
                {preview.headers.map((header, index) => (
                  <div key={index} className="flex items-center gap-3">
                    <span className="text-sm text-slate-600 w-40 truncate flex-shrink-0" title={header}>
                      {header}
                    </span>
                    <ArrowRight className="w-4 h-4 text-slate-300 flex-shrink-0" />
                    <select
                      value={mapping[index] || ''}
                      onChange={(e) => updateMapping(index, e.target.value)}
                      className="flex-1 px-3 py-1.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      {CLIENT_FIELDS.map((f) => (
                        <option key={f.value} value={f.value}>{f.label}</option>
                      ))}
                    </select>
                  </div>
                ))}
              </div>
            </div>

            {/* Preview table */}
            {preview.sampleRows.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-slate-700 mb-2">Preview (first {preview.sampleRows.length} rows):</h4>
                <div className="overflow-x-auto border border-slate-200 rounded-lg">
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="bg-slate-50">
                        {preview.headers.map((h, i) => (
                          <th key={i} className="px-3 py-2 text-left font-medium text-slate-600 whitespace-nowrap">
                            {mapping[i] ? (
                              <span className="text-blue-600">{CLIENT_FIELDS.find(f => f.value === mapping[i])?.label || mapping[i]}</span>
                            ) : (
                              <span className="text-slate-400 line-through">{h}</span>
                            )}
                          </th>
                        ))}
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {preview.sampleRows.map((row, ri) => (
                        <tr key={ri}>
                          {row.map((cell, ci) => (
                            <td key={ci} className={`px-3 py-2 whitespace-nowrap ${mapping[ci] ? 'text-slate-700' : 'text-slate-300'}`}>
                              {cell || '—'}
                            </td>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {!hasRequiredFields() && (
              <div className="flex items-center gap-2 p-3 bg-amber-50 text-amber-700 rounded-lg text-sm">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                You must map both "First Name" and "Last Name" columns
              </div>
            )}

            {error && (
              <div className="flex items-center gap-2 p-3 bg-red-50 text-red-700 rounded-lg text-sm">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {error}
              </div>
            )}

            <div className="flex justify-between pt-2">
              <button onClick={reset} className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors">
                ← Back
              </button>
              <button
                onClick={handleImport}
                disabled={!hasRequiredFields()}
                className="px-5 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50 transition-colors"
              >
                Import {preview.totalRows} Clients
              </button>
            </div>
          </div>
        )}

        {/* Step: Importing */}
        {step === 'importing' && (
          <div className="flex flex-col items-center justify-center py-8 gap-4">
            <LoadingSpinner size="lg" />
            <p className="text-sm text-slate-600">Importing clients...</p>
            <p className="text-xs text-slate-400">This may take a moment for large files</p>
          </div>
        )}

        {/* Step: Results */}
        {step === 'results' && result && (
          <div className="space-y-4">
            <div className="flex items-center gap-3 p-4 bg-emerald-50 rounded-lg">
              <CheckCircle2 className="w-8 h-8 text-emerald-600 flex-shrink-0" />
              <div>
                <p className="font-semibold text-emerald-800">Import Complete</p>
                <p className="text-sm text-emerald-700">
                  Successfully imported <strong>{result.imported}</strong> client{result.imported !== 1 ? 's' : ''}
                  {result.skipped > 0 && `, ${result.skipped} skipped`}
                </p>
              </div>
            </div>

            {result.errors.length > 0 && (
              <div className="space-y-2">
                <h4 className="text-sm font-medium text-slate-700">Issues ({result.errors.length}):</h4>
                <div className="max-h-40 overflow-y-auto space-y-1 p-3 bg-slate-50 rounded-lg">
                  {result.errors.map((err, i) => (
                    <p key={i} className="text-xs text-slate-600">{err}</p>
                  ))}
                </div>
              </div>
            )}

            <div className="flex justify-end pt-2">
              <button
                onClick={handleClose}
                className="px-5 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors"
              >
                Done
              </button>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}
