// Import & Export page

// ── Template definition ───────────────────────────────────────────────────────
const TX_HEADERS    = ['Date', 'Type', 'Amount (ZAR)', 'Category', 'Source', 'Note', 'Recurring'];
const TX_EXAMPLES   = [
  ['2026-01-15', 'expense', '1250.00', 'Groceries',  'Woolworths',   'Weekly shop',     ''],
  ['2026-01-16', 'income',  '45000.00','Salary',     'My Company',   'Monthly salary',  'monthly'],
  ['2026-01-17', 'expense', '800.00',  'Transport',  'Uber',         'Work commute',    ''],
];
const TX_NOTES = [
  ['--- INSTRUCTIONS ---'],
  ['Date: YYYY-MM-DD format (e.g. 2026-01-15)'],
  ['Type: "income" or "expense" only'],
  ['Amount: numbers only, no currency symbol (e.g. 1250.00)'],
  ['Recurring: leave blank, or "monthly" / "weekly"'],
  ['Delete these instruction rows before importing'],
];

// ── Import section ─────────────────────────────────────────────────────────────
const ImportSection = () => {
  const { addTransaction } = useAppState();
  const [dragging, setDragging]   = React.useState(false);
  const [preview,  setPreview]    = React.useState(null);   // { rows, errors }
  const [importing, setImporting] = React.useState(false);
  const [result,   setResult]     = React.useState(null);   // { imported, skipped, errors }
  const [fileErr,  setFileErr]    = React.useState('');
  const fileRef = React.useRef();

  // ── Template download ──────────────────────────────────────────────────────
  const downloadTemplate = () => {
    const wb = window.XLSX.utils.book_new();

    // Transactions sheet
    const txData = [TX_HEADERS, ...TX_EXAMPLES];
    const ws = window.XLSX.utils.aoa_to_sheet(txData);
    ws['!cols'] = [{ wch:14 },{ wch:10 },{ wch:14 },{ wch:16 },{ wch:18 },{ wch:22 },{ wch:12 }];
    window.XLSX.utils.book_append_sheet(wb, ws, 'Transactions');

    // Instructions sheet
    const wi = window.XLSX.utils.aoa_to_sheet(TX_NOTES);
    wi['!cols'] = [{ wch: 55 }];
    window.XLSX.utils.book_append_sheet(wb, wi, 'Instructions');

    window.XLSX.writeFile(wb, 'budget-import-template.xlsx');
  };

  // ── Parse uploaded file ────────────────────────────────────────────────────
  const parseFile = (file) => {
    setFileErr(''); setPreview(null); setResult(null);
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const wb   = window.XLSX.read(e.target.result, { type: 'binary', raw: false });
        const ws   = wb.Sheets[wb.SheetNames[0]];
        const data = window.XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' });

        // Find header row
        const headerIdx = data.findIndex(row =>
          row.some(c => String(c).toLowerCase().includes('date')) &&
          row.some(c => String(c).toLowerCase().includes('type')) &&
          row.some(c => String(c).toLowerCase().includes('amount'))
        );
        if (headerIdx === -1) { setFileErr('Could not find headers. Make sure you\'re using the Budget Builder template.'); return; }

        const headers = data[headerIdx].map(h => String(h).toLowerCase().trim());
        const col = (name) => headers.findIndex(h => h.includes(name));
        const iDate = col('date'), iType = col('type'), iAmt = col('amount');
        const iCat  = col('category'), iSrc = col('source'), iNote = col('note'), iRec = col('recurring');

        const rows = []; const errors = [];
        data.slice(headerIdx + 1).forEach((row, i) => {
          if (row.every(c => c === '' || c === null)) return; // skip blank rows
          const rawDate = String(row[iDate] || '').trim();
          const rawType = String(row[iType] || '').trim().toLowerCase();
          const rawAmt  = String(row[iAmt]  || '').trim().replace(/[^0-9.]/g, '');
          const lineNo  = headerIdx + i + 2;

          if (!rawDate.match(/^\d{4}-\d{2}-\d{2}$/))       { errors.push(`Row ${lineNo}: invalid date "${rawDate}" — use YYYY-MM-DD`); return; }
          if (!['income','expense'].includes(rawType))       { errors.push(`Row ${lineNo}: type must be "income" or "expense"`); return; }
          if (!rawAmt || isNaN(Number(rawAmt)))              { errors.push(`Row ${lineNo}: invalid amount "${row[iAmt]}"`); return; }

          rows.push({
            date:      rawDate,
            type:      rawType,
            amount:    Number(rawAmt),
            category:  iCat  >= 0 ? String(row[iCat]  || '').trim() : '',
            source:    iSrc  >= 0 ? String(row[iSrc]  || '').trim() : '',
            note:      iNote >= 0 ? String(row[iNote] || '').trim() : '',
            recurring: iRec  >= 0 ? String(row[iRec]  || '').trim() : '',
          });
        });
        setPreview({ rows, errors });
      } catch (err) { setFileErr('Could not read file: ' + err.message); }
    };
    reader.readAsBinaryString(file);
  };

  const handleFile = (file) => {
    if (!file) return;
    const ext = file.name.split('.').pop().toLowerCase();
    if (!['csv','xlsx','xls'].includes(ext)) { setFileErr('Please upload a .xlsx, .xls or .csv file.'); return; }
    parseFile(file);
  };

  const handleDrop = (e) => {
    e.preventDefault(); setDragging(false);
    handleFile(e.dataTransfer.files[0]);
  };

  // ── Commit import ──────────────────────────────────────────────────────────
  const commitImport = async () => {
    if (!preview?.rows?.length) return;
    setImporting(true);
    let imported = 0, skipped = 0;
    for (const row of preview.rows) {
      try { await addTransaction(row); imported++; }
      catch { skipped++; }
    }
    setImporting(false);
    setResult({ imported, skipped });
    setPreview(null);
  };

  return (
    <div className="card card-pad-lg fade-up" style={{ marginBottom: 20 }}>
      <div className="card-title">Import transactions</div>
      <p style={{ fontSize: 13.5, color: 'var(--ink-3)', margin: '0 0 20px', lineHeight: 1.6 }}>
        Download the template, fill it in with your transactions, then upload it here. The app will preview everything before importing.
      </p>

      {/* Step 1 — Download template */}
      <div style={{ display:'flex', alignItems:'center', gap:14, padding:'14px 16px', background:'var(--surface-2)', borderRadius:12, border:'1px solid var(--line)', marginBottom:16 }}>
        <div style={{ width:38, height:38, borderRadius:10, background:'var(--mint-soft)', border:'1px solid var(--mint)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:18 }}>📥</div>
        <div style={{ flex:1 }}>
          <div style={{ fontWeight:500, fontSize:14, marginBottom:2 }}>Step 1 — Download the template</div>
          <div style={{ fontSize:12.5, color:'var(--ink-3)' }}>Pre-formatted Excel file with example rows and instructions</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={downloadTemplate} style={{ display:'flex', alignItems:'center', gap:6, flexShrink:0 }}>
          <IDownload size={12}/> Template
        </button>
      </div>

      {/* Step 2 — Upload */}
      <div style={{ fontWeight:500, fontSize:14, marginBottom:10 }}>Step 2 — Upload your filled template</div>
      <div
        onDragOver={e => { e.preventDefault(); setDragging(true); }}
        onDragLeave={() => setDragging(false)}
        onDrop={handleDrop}
        onClick={() => fileRef.current.click()}
        style={{
          border: `2px dashed ${dragging ? 'var(--ink)' : 'var(--line)'}`,
          borderRadius: 12, padding: '28px 20px', textAlign: 'center',
          cursor: 'pointer', transition: 'border-color 0.15s, background 0.15s',
          background: dragging ? 'var(--surface-2)' : 'transparent',
          marginBottom: 14,
        }}
      >
        <div style={{ fontSize: 28, marginBottom: 8 }}>📂</div>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 4 }}>
          Drop your file here, or click to browse
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>.xlsx, .xls or .csv</div>
        <input ref={fileRef} type="file" accept=".xlsx,.xls,.csv" style={{ display:'none' }}
          onChange={e => handleFile(e.target.files[0])} />
      </div>

      {fileErr && (
        <div style={{ background:'#fff1f0', border:'1px solid #fca5a5', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#b91c1c', marginBottom:14 }}>
          {fileErr}
        </div>
      )}

      {/* Preview */}
      {preview && (
        <div>
          {preview.errors.length > 0 && (
            <div style={{ background:'#fff7ed', border:'1px solid #fed7aa', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#c2410c', marginBottom:14 }}>
              <div style={{ fontWeight:500, marginBottom:4 }}>⚠ {preview.errors.length} row{preview.errors.length>1?'s':''} will be skipped:</div>
              {preview.errors.map((e,i) => <div key={i} style={{ marginTop:2 }}>· {e}</div>)}
            </div>
          )}

          {preview.rows.length > 0 && (
            <div style={{ marginBottom:14 }}>
              <div style={{ fontWeight:500, fontSize:13.5, marginBottom:10 }}>
                Preview — {preview.rows.length} transaction{preview.rows.length>1?'s':''} ready to import
              </div>
              <div style={{ overflowX:'auto', borderRadius:10, border:'1px solid var(--line)' }}>
                <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12.5 }}>
                  <thead>
                    <tr style={{ background:'var(--surface-2)', borderBottom:'1px solid var(--line)' }}>
                      {['Date','Type','Amount','Category','Source','Note'].map(h => (
                        <th key={h} style={{ padding:'8px 12px', textAlign:'left', fontWeight:500, color:'var(--ink-2)', whiteSpace:'nowrap' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {preview.rows.slice(0,8).map((r,i) => (
                      <tr key={i} style={{ borderBottom:'1px solid var(--line-2)' }}>
                        <td style={{ padding:'8px 12px', color:'var(--ink-3)' }}>{r.date}</td>
                        <td style={{ padding:'8px 12px' }}>
                          <span style={{ fontSize:11, fontWeight:500, padding:'2px 8px', borderRadius:20,
                            background: r.type==='income' ? 'var(--mint-soft)' : 'var(--coral-soft)',
                            color:      r.type==='income' ? 'var(--mint-deep)' : 'var(--coral)',
                          }}>{r.type}</span>
                        </td>
                        <td style={{ padding:'8px 12px', fontFamily:'var(--font-mono)', fontWeight:500 }}>
                          {fmtZARShort(r.amount)}
                        </td>
                        <td style={{ padding:'8px 12px', color:'var(--ink-2)' }}>{r.category}</td>
                        <td style={{ padding:'8px 12px', color:'var(--ink-3)' }}>{r.source}</td>
                        <td style={{ padding:'8px 12px', color:'var(--ink-3)' }}>{r.note}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {preview.rows.length > 8 && (
                  <div style={{ padding:'8px 12px', fontSize:12, color:'var(--ink-3)', borderTop:'1px solid var(--line-2)', background:'var(--surface-2)' }}>
                    + {preview.rows.length - 8} more rows
                  </div>
                )}
              </div>
              <div style={{ display:'flex', gap:10, marginTop:14 }}>
                <button className="btn btn-primary" onClick={commitImport} disabled={importing} style={{ display:'flex', alignItems:'center', gap:8 }}>
                  {importing ? 'Importing…' : `Import ${preview.rows.length} transaction${preview.rows.length>1?'s':''}`}
                </button>
                <button className="btn btn-ghost" onClick={() => { setPreview(null); fileRef.current.value = ''; }}>Cancel</button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Result */}
      {result && (
        <div style={{ background:'#f0fdf4', border:'1px solid #86efac', borderRadius:10, padding:'14px 16px', fontSize:13.5 }}>
          <div style={{ fontWeight:500, color:'#166534', marginBottom:4, display:'flex', alignItems:'center', gap:6 }}>
            <ICheck size={14}/> Import complete
          </div>
          <div style={{ color:'#15803d' }}>
            {result.imported} transaction{result.imported!==1?'s':''} imported successfully
            {result.skipped > 0 && ` · ${result.skipped} skipped`}
          </div>
        </div>
      )}
    </div>
  );
};

// ── Main page ──────────────────────────────────────────────────────────────────
const PageExport = () => {
  const { state } = useAppState();
  const [exported, setExported] = React.useState('');

  const txRows = () => [
    ['Date', 'Type', 'Amount (ZAR)', 'Category', 'Source', 'Note', 'Recurring'],
    ...state.transactions.map(t => [t.date, t.type, t.amount, t.category||'', t.source||'', t.note||'', t.recurring||'']),
  ];
  const debtRows = () => [
    ['Name', 'Balance (ZAR)', 'Original Balance (ZAR)', 'APR %', 'Minimum Payment (ZAR)'],
    ...state.debts.map(d => [d.name, d.balance, d.originalBalance, d.apr, d.minimum]),
  ];
  const goalRows = () => [
    ['Name', 'Target (ZAR)', 'Saved (ZAR)', 'Deadline'],
    ...state.goals.map(g => [g.name, g.target, g.saved, g.deadline||'']),
  ];
  const billRows = () => [
    ['Name', 'Amount (ZAR)', 'Day of Month', 'Category'],
    ...state.bills.map(b => [b.name, b.amount, b.dayOfMonth, b.category||'']),
  ];

  const trigger = (blob, filename) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = filename; a.click();
    URL.revokeObjectURL(url);
  };

  const downloadCSV = (filename, rows) => {
    const csv = rows.map(r => r.map(cell => {
      const s = String(cell ?? '');
      return s.includes(',') || s.includes('"') || s.includes('\n') ? `"${s.replace(/"/g,'""')}"` : s;
    }).join(',')).join('\n');
    trigger(new Blob(['﻿'+csv], { type:'text/csv;charset=utf-8;' }), filename);
  };

  const downloadXLSX = (filename, sheets) => {
    const wb = window.XLSX.utils.book_new();
    sheets.forEach(({ name, rows }) => {
      const ws = window.XLSX.utils.aoa_to_sheet(rows);
      window.XLSX.utils.book_append_sheet(wb, ws, name);
    });
    window.XLSX.writeFile(wb, filename);
  };

  const flash = (label) => { setExported(label); setTimeout(() => setExported(''), 2500); };

  const sections = [
    { id:'transactions', label:'Transactions', count:state.transactions.length, icon:'↕', rows:txRows },
    { id:'debts',        label:'Debts',        count:state.debts.length,        icon:'💳', rows:debtRows },
    { id:'goals',        label:'Goals',        count:state.goals.length,        icon:'🎯', rows:goalRows },
    { id:'bills',        label:'Bills',        count:state.bills.length,        icon:'📅', rows:billRows },
  ];

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title"><span className="serif">Import & Export</span></h1>
          <div className="page-sub">Bring data in or take it out</div>
        </div>
      </div>

      <ImportSection />

      {/* Divider */}
      <div style={{ display:'flex', alignItems:'center', gap:12, margin:'8px 0 20px' }}>
        <div style={{ flex:1, height:1, background:'var(--line)' }}/>
        <span style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)' }}>Export</span>
        <div style={{ flex:1, height:1, background:'var(--line)' }}/>
      </div>

      {/* Export all */}
      <div className="card card-pad-lg fade-up" style={{ marginBottom:20 }}>
        <div className="card-title">Export everything</div>
        <p style={{ fontSize:13.5, color:'var(--ink-3)', margin:'0 0 20px', lineHeight:1.6 }}>
          Download all your transactions, debts, goals, and bills in one file. Excel exports use separate sheets.
        </p>
        <div className="row" style={{ gap:10, flexWrap:'wrap' }}>
          <button className="btn btn-primary" onClick={() => { downloadXLSX('budget-export.xlsx',[{name:'Transactions',rows:txRows()},{name:'Debts',rows:debtRows()},{name:'Goals',rows:goalRows()},{name:'Bills',rows:billRows()}]); flash('all-xlsx'); }} style={{ display:'flex', alignItems:'center', gap:8 }}>
            <IDownload size={14}/> Excel (.xlsx)
          </button>
          <button className="btn btn-ghost" onClick={() => { downloadCSV('transactions.csv',txRows()); downloadCSV('debts.csv',debtRows()); downloadCSV('goals.csv',goalRows()); downloadCSV('bills.csv',billRows()); flash('all-csv'); }} style={{ display:'flex', alignItems:'center', gap:8 }}>
            <IDownload size={14}/> CSV files
          </button>
        </div>
        {(exported==='all-xlsx'||exported==='all-csv') && (
          <div style={{ marginTop:14, fontSize:13, color:'var(--mint-deep)', display:'flex', alignItems:'center', gap:6 }}>
            <ICheck size={13}/> Downloaded successfully
          </div>
        )}
      </div>

      {/* Per-section */}
      <div style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', marginBottom:12 }}>Export by section</div>
      <div className="grid stagger" style={{ gridTemplateColumns:'repeat(2, 1fr)', gap:14 }}>
        {sections.map(s => (
          <div key={s.id} className="card card-pad-lg fade-up">
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
              <div style={{ width:36, height:36, borderRadius:10, background:'var(--surface-2)', border:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16 }}>{s.icon}</div>
              <div>
                <div style={{ fontWeight:500, fontSize:14 }}>{s.label}</div>
                <div style={{ fontSize:12, color:'var(--ink-3)' }}>{s.count} record{s.count!==1?'s':''}</div>
              </div>
            </div>
            <div className="row" style={{ gap:8 }}>
              <button className="btn btn-ghost btn-sm" style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:6 }} disabled={s.count===0}
                onClick={() => { downloadXLSX(`${s.id}.xlsx`,[{name:s.label,rows:s.rows()}]); flash(`${s.id}-xlsx`); }}>
                <IDownload size={12}/> Excel
              </button>
              <button className="btn btn-ghost btn-sm" style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', gap:6 }} disabled={s.count===0}
                onClick={() => { downloadCSV(`${s.id}.csv`, s.rows()); flash(`${s.id}-csv`); }}>
                <IDownload size={12}/> CSV
              </button>
            </div>
            {(exported===`${s.id}-xlsx`||exported===`${s.id}-csv`) && (
              <div style={{ marginTop:10, fontSize:12, color:'var(--mint-deep)', display:'flex', alignItems:'center', gap:5 }}>
                <ICheck size={12}/> Downloaded
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { PageExport });
