import { useState, useRef } from 'react';
import Papa from 'papaparse';
import toast from 'react-hot-toast';
import { Upload, X, FileText, AlertCircle, CheckCircle } from 'lucide-react';

type ListType = 'bnp' | 'b2b' | 'b2c';

interface Props {
  listType: ListType;
  userId: string;
  onComplete: () => void;
  onClose: () => void;
}

interface ImportResult {
  imported: number;
  skipped: number;
  errors: { email: string; reason: string }[];
}

// Schema fields per list type
const SCHEMA: Record<ListType, string[]> = {
  bnp: ['first_name', 'last_name', 'email', 'phone', 'company', 'category', 'tag'],
  b2b: ['first_name', 'last_name', 'email', 'phone_office', 'company_name', 'job_title', 'industry', 'website', 'street_address', 'city', 'state', 'zip_code', 'tag'],
  b2c: ['first_name', 'last_name', 'email', 'phone_mobile', 'street_address', 'city', 'state', 'zip_code', 'service_interest', 'last_service_date', 'tag'],
};

// Aliases: DB field → list of CSV column headers that map to it (lowercased)
const ALIASES: Record<string, string[]> = {
  first_name:         ['first_name', 'firstname', 'first name', 'first', 'fname'],
  last_name:          ['last_name', 'lastname', 'last name', 'last', 'surname', 'lname'],
  email:              ['email', 'email address', 'e-mail', 'emailaddress', 'email_address'],
  tag:                ['tag', 'tags', 'label', 'labels'],
  // BNP
  phone:              ['phone', 'phone_number', 'phone number', 'telephone', 'tel', 'business phone'],
  company:            ['company', 'company_name', 'company name', 'organization', 'business', 'employer'],
  category:           ['category', 'type', 'business type', 'business_type'],
  // B2B
  phone_office:       ['phone_office', 'phone', 'office phone', 'office_phone', 'business phone', 'work phone'],
  company_name:       ['company_name', 'company', 'company name', 'organization', 'business'],
  job_title:          ['job_title', 'job title', 'title', 'position', 'role'],
  industry:           ['industry', 'sector', 'field'],
  website:            ['website', 'web', 'url', 'web address', 'website_url'],
  street_address:     ['street_address', 'street', 'address', 'address1', 'address 1', 'street address'],
  city:               ['city'],
  state:              ['state', 'state_code'],
  zip_code:           ['zip_code', 'zip', 'postal', 'postal_code', 'postal code', 'zipcode'],
  // B2C
  phone_mobile:       ['phone_mobile', 'phone', 'mobile', 'cell', 'mobile_phone', 'cell_phone', 'mobile phone', 'cell phone'],
  service_interest:   ['service_interest', 'service', 'interest', 'services', 'service interest'],
  last_service_date:  ['last_service_date', 'last service', 'service_date', 'service date'],
};

function mapRow(rawRow: Record<string, string>, fields: string[]): Record<string, string> {
  const lowered: Record<string, string> = {};
  for (const [k, v] of Object.entries(rawRow)) {
    const key = k.trim().toLowerCase();
    if (!key) continue;
    lowered[key] = v != null ? String(v).trim() : '';
  }
  const mapped: Record<string, string> = {};
  for (const field of fields) {
    const aliases = ALIASES[field] || [field];
    for (const alias of aliases) {
      if (lowered[alias] !== undefined) {
        mapped[field] = lowered[alias];
        break;
      }
    }
  }
  return mapped;
}

const LIST_LABELS: Record<ListType, string> = { bnp: 'BNP', b2b: 'B2B', b2c: 'B2C' };

const CSVImport = ({ listType, userId, onComplete, onClose }: Props) => {
  const [rows, setRows] = useState<Record<string, string>[]>([]);
  const [fileName, setFileName] = useState('');
  const [importing, setImporting] = useState(false);
  const [result, setResult] = useState<ImportResult | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const fields = SCHEMA[listType];

  const handleFile = (file: File) => {
    if (!file.name.endsWith('.csv')) {
      toast.error('Please select a CSV file.');
      return;
    }
    setFileName(file.name);
    setResult(null);

    Papa.parse<Record<string, string>>(file, {
      header: true,
      skipEmptyLines: true,
      complete: ({ data }) => {
        const mapped = data.map(row => mapRow(row, fields));
        setRows(mapped);
      },
      error: (err) => toast.error('CSV parse error: ' + err.message),
    });
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  };

  const handleImport = async () => {
    if (rows.length === 0) return;
    setImporting(true);
    try {
      const response = await fetch(`/api/import/${listType}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ records: rows, userId }),
      });
      const data: ImportResult = await response.json();
      if (!response.ok) throw new Error((data as any).error || 'Import failed');
      setResult(data);
      if (data.imported > 0) onComplete();
    } catch (err: any) {
      toast.error('Import failed: ' + err.message);
    } finally {
      setImporting(false);
    }
  };

  const emailCount = rows.filter(r => r.email).length;
  const noEmailCount = rows.length - emailCount;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">

        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-100">
          <div className="flex items-center gap-3">
            <FileText className="text-blue-500" size={22} />
            <div>
              <h2 className="text-lg font-bold text-slate-800">Import CSV — {LIST_LABELS[listType]}</h2>
              <p className="text-[10px] uppercase tracking-widest font-bold text-slate-400">
                Emails validated via DeBounce before inserting
              </p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 rounded-xl hover:bg-slate-100 text-slate-400">
            <X size={20} />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-6 space-y-5">

          {/* Drop zone */}
          {!result && (
            <div
              onDrop={handleDrop}
              onDragOver={e => e.preventDefault()}
              onClick={() => fileInputRef.current?.click()}
              className="border-2 border-dashed border-slate-200 rounded-2xl p-10 text-center cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-colors"
            >
              <Upload className="mx-auto text-slate-300 mb-3" size={32} />
              {fileName ? (
                <p className="font-bold text-slate-700">{fileName}</p>
              ) : (
                <p className="text-slate-400 text-sm">Drop a CSV file here or <span className="text-blue-600 font-bold">browse</span></p>
              )}
              <p className="text-[10px] text-slate-300 mt-2 uppercase tracking-widest">
                Columns auto-detected by header name
              </p>
              <input ref={fileInputRef} type="file" accept=".csv" className="hidden" onChange={e => { const f = e.target.files?.[0]; if (f) handleFile(f); }} />
            </div>
          )}

          {/* Preview */}
          {rows.length > 0 && !result && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <p className="text-sm font-bold text-slate-700">{rows.length} rows parsed</p>
                <div className="flex gap-3 text-xs">
                  <span className="text-green-600 font-bold">{emailCount} with email</span>
                  {noEmailCount > 0 && <span className="text-amber-500 font-bold">{noEmailCount} missing email (will skip)</span>}
                </div>
              </div>

              {/* Column mapping display */}
              <div className="bg-slate-50 rounded-xl p-4">
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Fields detected</p>
                <div className="flex flex-wrap gap-2">
                  {fields.map(f => {
                    const hasData = rows.some(r => r[f]);
                    return (
                      <span key={f} className={`px-2 py-1 rounded-lg text-[10px] font-bold ${hasData ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-400'}`}>
                        {f.replace(/_/g, ' ')}
                      </span>
                    );
                  })}
                </div>
              </div>

              {/* Sample rows */}
              <div className="overflow-x-auto rounded-xl border border-slate-100">
                <table className="w-full text-xs">
                  <thead className="bg-slate-50">
                    <tr>
                      {['first_name', 'last_name', 'email'].map(f => (
                        <th key={f} className="px-3 py-2 text-left font-bold text-slate-500 uppercase tracking-wider text-[10px]">{f.replace(/_/g,' ')}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {rows.slice(0, 5).map((r, i) => (
                      <tr key={i} className="border-t border-slate-50">
                        <td className="px-3 py-2 text-slate-700">{r.first_name || '—'}</td>
                        <td className="px-3 py-2 text-slate-700">{r.last_name || '—'}</td>
                        <td className="px-3 py-2 text-slate-500 font-mono">{r.email || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {rows.length > 5 && (
                  <p className="px-3 py-2 text-[10px] text-slate-400 italic border-t border-slate-50">
                    …and {rows.length - 5} more rows
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Results */}
          {result && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-green-50 border border-green-100 rounded-2xl p-5 text-center">
                  <CheckCircle className="mx-auto text-green-500 mb-2" size={28} />
                  <p className="text-3xl font-black text-green-700">{result.imported}</p>
                  <p className="text-[10px] uppercase tracking-widest font-bold text-green-500 mt-1">Records Imported</p>
                </div>
                <div className="bg-amber-50 border border-amber-100 rounded-2xl p-5 text-center">
                  <AlertCircle className="mx-auto text-amber-500 mb-2" size={28} />
                  <p className="text-3xl font-black text-amber-700">{result.skipped}</p>
                  <p className="text-[10px] uppercase tracking-widest font-bold text-amber-500 mt-1">Skipped (Invalid)</p>
                </div>
              </div>

              {result.errors.length > 0 && (
                <div className="bg-slate-50 rounded-xl p-4 max-h-40 overflow-y-auto">
                  <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Skipped addresses</p>
                  {result.errors.map((e, i) => (
                    <div key={i} className="flex justify-between text-xs py-1 border-b border-slate-100 last:border-0">
                      <span className="font-mono text-slate-600">{e.email}</span>
                      <span className="text-slate-400 ml-4">{e.reason}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-6 border-t border-slate-100 flex gap-3">
          {!result ? (
            <>
              <button
                onClick={handleImport}
                disabled={importing || emailCount === 0}
                className="flex-1 bg-blue-600 text-white py-3 rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-blue-700 transition-colors disabled:opacity-50"
              >
                {importing
                  ? `Validating & importing… (this may take a moment)`
                  : `Import ${emailCount} Record${emailCount !== 1 ? 's' : ''}`}
              </button>
              <button onClick={onClose} className="px-6 bg-slate-100 text-slate-400 py-3 rounded-2xl font-black text-xs uppercase tracking-widest">
                Cancel
              </button>
            </>
          ) : (
            <button onClick={onClose} className="flex-1 bg-slate-900 text-white py-3 rounded-2xl font-black text-xs uppercase tracking-widest hover:bg-black transition-colors">
              Done
            </button>
          )}
        </div>

      </div>
    </div>
  );
};

export default CSVImport;
