// crm-import.jsx — Import Modal (CSV / Excel)
const IMPORT_CONFIG = {
  leads: {
    label: 'Leads',
    endpoint: '/api/import/leads',
    required: ['Company Name'],
    columns: [
      ['Company Name *', 'Contact Name', 'Title', 'Email', 'Phone'],
      ['Industry', 'Employee Count', 'Lead Source', 'Stage', 'Estimated Value'],
      ['Follow Up Date', 'Assigned Rep', 'Hardware Interest', 'Address', 'Notes'],
    ],
    notes: [
      'Stage: lead · contacted · demo · proposal · negotiation · won · lost (defaults to "lead")',
      'Assigned Rep: match by full name or email address',
      'Hardware Interest: comma-separated values within the cell',
      'Follow Up Date: any standard date format (e.g. 2025-06-15)',
    ],
  },
  accounts: {
    label: 'Accounts',
    endpoint: '/api/import/accounts',
    required: ['Company Name'],
    columns: [
      ['Company Name *', 'Address', 'Industry', 'Employee Count'],
      ['Contract Value', 'Single Purchase Value', 'Contract Start', 'Contract End'],
      ['Uri', 'Assigned Rep', 'Notes'],
    ],
    notes: [
      'Contract Value: monthly/recurring revenue amount',
      'Contract Start / End: any standard date format (e.g. 2025-01-01)',
      'Assigned Rep: match by full name or email address',
      'Uri: AoD system identifier used for billing import matching (e.g. 25-cintime)',
    ],
  },
  sales: {
    label: 'Sales',
    endpoint: '/api/import/sales',
    required: ['Account', 'Amount'],
    columns: [
      ['Account *', 'Amount *', 'Sale Date', 'Description', 'Single Purchase'],
    ],
    notes: [
      'Account: must match an existing account company name exactly',
      'Amount: numeric value (e.g. 1500 or 1500.00)',
      'Sale Date: any standard date format — defaults to today if blank',
      'Single Purchase: yes / no / true / false / 1 / 0 — defaults to No',
    ],
  },
  tickets: {
    label: 'Tickets',
    endpoint: '/api/import/tickets',
    required: ['Subject'],
    columns: [
      ['Subject *', 'Description', 'Category'],
      ['Priority', 'Status', 'Account'],
    ],
    notes: [
      'Priority: low · medium · high · urgent (defaults to "medium")',
      'Status: open · in-progress · pending · resolved · closed (defaults to "open")',
      'Account: match by company name — ticket will be unlinked if not found',
    ],
  },
};

function ImportModal({ type, onClose, onDone, inline = false }) {
  const cfg = IMPORT_CONFIG[type];
  const [file, setFile] = useState(null);
  const [dragging, setDragging] = useState(false);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const fileRef = React.useRef();

  const handleFile = (f) => {
    if (!f) return;
    const ext = f.name.split('.').pop().toLowerCase();
    if (!['csv','xlsx','xls','xlsm'].includes(ext)) {
      setError('Please select a .csv or .xlsx file.');
      return;
    }
    setFile(f);
    setResult(null);
    setError(null);
  };

  const onDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    handleFile(e.dataTransfer.files[0]);
  };

  const doImport = async () => {
    if (!file) return;
    setLoading(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch(cfg.endpoint, { method: 'POST', body: fd });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Import failed');
      setResult(data);
      if (data.imported > 0) onDone();
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  const reset = () => { setFile(null); setResult(null); setError(null); };

  const inner = (
    <>
        <div className="modal-hd" style={inline ? {padding:'0 0 16px 0',borderBottom:'1px solid var(--g200)',marginBottom:4} : {}}>
          <div className="modal-title">Import {cfg.label}</div>
          {!inline && <button className="modal-close" onClick={onClose}>×</button>}
        </div>

        <div className="modal-body" style={{paddingBottom:0}}>
          {!result ? (
            <>
              {/* Drop zone */}
              <div
                onDragOver={e => { e.preventDefault(); setDragging(true); }}
                onDragLeave={() => setDragging(false)}
                onDrop={onDrop}
                onClick={() => fileRef.current?.click()}
                style={{
                  border: `2px dashed ${dragging ? 'var(--navy)' : file ? 'var(--green)' : 'var(--g200)'}`,
                  borderRadius: 8, padding: '28px 20px', textAlign: 'center',
                  cursor: 'pointer', marginBottom: 20, transition: 'border-color .15s',
                  background: dragging ? 'var(--off)' : 'transparent',
                }}>
                <input ref={fileRef} type="file" accept=".csv,.xlsx,.xls,.xlsm"
                  style={{display:'none'}} onChange={e => handleFile(e.target.files[0])} />
                <div style={{fontSize:28,marginBottom:8}}>{file ? '📄' : '📂'}</div>
                {file ? (
                  <div>
                    <div style={{fontWeight:700,color:'var(--navy)',fontSize:14}}>{file.name}</div>
                    <div style={{fontSize:12,color:'var(--g400)',marginTop:4}}>
                      {(file.size / 1024).toFixed(1)} KB · click to change
                    </div>
                  </div>
                ) : (
                  <div>
                    <div style={{fontWeight:600,color:'var(--navy)',fontSize:14}}>Drop file here or click to browse</div>
                    <div style={{fontSize:12,color:'var(--g400)',marginTop:4}}>Supports .csv and .xlsx</div>
                  </div>
                )}
              </div>

              {error && (
                <div style={{background:'#fef2f2',border:'1px solid #fca5a5',borderRadius:6,padding:'10px 14px',marginBottom:16,fontSize:13,color:'#991b1b'}}>
                  ⚠️ {error}
                </div>
              )}

              {/* Column reference */}
              <div style={{fontSize:12,color:'var(--g600)',marginBottom:6,fontWeight:600}}>Expected column headers</div>
              <div style={{background:'var(--off)',borderRadius:6,padding:'12px 14px',marginBottom:16,fontFamily:'monospace',fontSize:12,color:'var(--g600)'}}>
                {cfg.columns.map((row, i) => (
                  <div key={i} style={{marginBottom: i < cfg.columns.length-1 ? 4 : 0}}>
                    {row.join(' · ')}
                  </div>
                ))}
              </div>

              <div style={{fontSize:12,color:'var(--g400)',marginBottom:16}}>
                {cfg.notes.map((n, i) => <div key={i} style={{marginBottom:3}}>• {n}</div>)}
              </div>
            </>
          ) : (
            /* Results */
            <div>
              <div style={{display:'flex',gap:16,marginBottom:20}}>
                <div style={{flex:1,background:'#f0fdf4',border:'1px solid #86efac',borderRadius:8,padding:'14px 16px',textAlign:'center'}}>
                  <div style={{fontSize:24,fontWeight:800,color:'var(--green)'}}>{result.imported}</div>
                  <div style={{fontSize:12,color:'#16a34a',fontWeight:600}}>Imported</div>
                </div>
                <div style={{flex:1,background:'var(--off)',border:'1px solid var(--g200)',borderRadius:8,padding:'14px 16px',textAlign:'center'}}>
                  <div style={{fontSize:24,fontWeight:800,color:'var(--g400)'}}>{result.skipped}</div>
                  <div style={{fontSize:12,color:'var(--g500)',fontWeight:600}}>Skipped</div>
                </div>
                {result.errors?.length > 0 && (
                  <div style={{flex:1,background:'#fef2f2',border:'1px solid #fca5a5',borderRadius:8,padding:'14px 16px',textAlign:'center'}}>
                    <div style={{fontSize:24,fontWeight:800,color:'var(--red)'}}>{result.errors.length}</div>
                    <div style={{fontSize:12,color:'#991b1b',fontWeight:600}}>Errors</div>
                  </div>
                )}
              </div>

              {result.errors?.length > 0 && (
                <div style={{background:'#fef2f2',border:'1px solid #fca5a5',borderRadius:6,padding:'12px 14px',marginBottom:16}}>
                  <div style={{fontWeight:600,fontSize:12,color:'#991b1b',marginBottom:8}}>Row errors:</div>
                  {result.errors.length > 50 && (
                    <div style={{marginBottom:4,fontWeight:600}}>Showing the first 50 of {result.errors.length} errors:</div>
                  )}
                  {result.errors.slice(0, 50).map((e, i) => (
                    <div key={i} style={{fontSize:12,color:'#7f1d1d',marginBottom:3}}>• {e}</div>
                  ))}
                </div>
              )}

              {result.imported === 0 && result.skipped === 0 && (
                <div style={{color:'var(--g400)',fontSize:13,textAlign:'center',padding:'8px 0'}}>
                  No rows found in file. Make sure the first row contains column headers.
                </div>
              )}
            </div>
          )}
        </div>

        <div className={inline ? 'modal-footer' : 'modal-footer'} style={inline ? {padding:'16px 0 0 0'} : {}}>
          {result ? (
            <>
              <button className="btn btn-ghost" onClick={reset}>Import Another</button>
              {!inline && <button className="btn btn-primary" onClick={onClose}>Done</button>}
            </>
          ) : (
            <>
              {!inline && <button className="btn btn-ghost" onClick={onClose}>Cancel</button>}
              <button className="btn btn-primary" onClick={doImport} disabled={!file || loading}>
                {loading ? 'Importing…' : 'Import'}
              </button>
            </>
          )}
        </div>
      </>
  );

  if (inline) return <div className="card card-pad">{inner}</div>;

  return (
    <div className="modal-overlay" {...overlayClose(onClose)}>
      <div className="modal-panel" style={{maxWidth:560}} onClick={e => e.stopPropagation()}>
        {inner}
      </div>
    </div>
  );
}

Object.assign(window, { ImportModal });
