// Tax Report — SA tax year (1 March – 28/29 Feb), deductible transactions summary + export.

// SA tax year: 1 March (year-1) → 28/29 Feb (year)
// "2025 tax year" = 1 Mar 2024 → 28 Feb 2025
const taxYearRange = (endYear) => ({
  start: new Date(`${endYear - 1}-03-01`),
  end:   new Date(`${endYear}-02-28T23:59:59`),
  label: `${endYear - 1} / ${endYear}`,
});

const DEDUCTIBLE_TYPES = [
  { id: 'medical',     label: 'Medical',      color: 'var(--sky)',    soft: 'var(--sky-soft)'    },
  { id: 'travel',      label: 'Travel',       color: 'var(--violet)', soft: 'var(--violet-soft)' },
  { id: 'home-office', label: 'Home Office',  color: 'var(--amber)',  soft: 'var(--amber-soft)'  },
  { id: 'donations',   label: 'Donations',    color: 'var(--mint)',   soft: 'var(--mint-soft)'   },
  { id: 'business',    label: 'Business',     color: 'var(--coral)',  soft: 'var(--coral-soft)'  },
  { id: 'other',       label: 'Other',        color: 'var(--ink-3)',  soft: 'var(--surface-2)'   },
];

const PageTax = () => {
  const { state, profile } = useAppState();

  // SA tax year selector — current and 3 previous
  const currentEndYear = (() => {
    const now = today();
    return now.getMonth() >= 2 ? now.getFullYear() + 1 : now.getFullYear();
  })();
  const yearOptions = [0, 1, 2, 3].map(i => currentEndYear - i);
  const [endYear,    setEndYear]    = React.useState(currentEndYear);
  const [typeFilter, setTypeFilter] = React.useState('all');

  const range = taxYearRange(endYear);

  // Filter deductible transactions within the selected tax year
  const deductibleTxs = React.useMemo(() => {
    return state.transactions.filter(t => {
      if (!t.deductible) return false;
      const d = new Date(t.date);
      return d >= range.start && d <= range.end;
    }).sort((a, b) => new Date(b.date) - new Date(a.date));
  }, [state.transactions, endYear]);

  // Totals by type
  const byType = React.useMemo(() => {
    const m = {};
    DEDUCTIBLE_TYPES.forEach(dt => { m[dt.id] = 0; });
    deductibleTxs.forEach(t => {
      const key = t.deductibleType || 'other';
      m[key] = (m[key] || 0) + t.amount;
    });
    return m;
  }, [deductibleTxs]);

  const totalDeductible = deductibleTxs.reduce((s, t) => s + t.amount, 0);

  // Filtered list for table
  const visibleTxs = typeFilter === 'all'
    ? deductibleTxs
    : deductibleTxs.filter(t => (t.deductibleType || 'other') === typeFilter);

  // CSV export
  const exportCSV = () => {
    const name = profile?.displayName || 'User';
    const rows = [
      [`Tax Deductible Expenses — ${name}`],
      [`SA Tax Year: ${range.label} (1 March ${endYear - 1} – 28 Feb ${endYear})`],
      [`Generated: ${new Date().toLocaleDateString('en-ZA')}`],
      [],
      ['Date', 'Description', 'Category', 'Type', 'Amount'],
      ...visibleTxs.map(t => {
        const cat = categoryById(t.category);
        const dt  = DEDUCTIBLE_TYPES.find(d => d.id === t.deductibleType);
        return [
          new Date(t.date).toLocaleDateString('en-ZA'),
          t.note || cat?.label || '',
          cat?.label || '',
          dt?.label || 'Other',
          t.amount.toFixed(2),
        ];
      }),
      [],
      ['', '', '', 'TOTAL', totalDeductible.toFixed(2)],
    ];

    const csv = rows.map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url;
    a.download = `tax-deductibles-${range.label.replace(' / ', '-')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      {/* ── Header ── */}
      <div className="topbar">
        <div>
          <h1 className="page-title">Tax <span className="serif">Report</span></h1>
          <div className="page-sub">SA tax year · deductible expenses summary</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {/* Tax year selector */}
          <select
            value={endYear}
            onChange={e => setEndYear(Number(e.target.value))}
            style={{
              padding: '7px 12px', borderRadius: 8, border: '1.5px solid var(--line)',
              background: 'var(--surface)', fontSize: 13.5, color: 'var(--ink)',
              fontFamily: 'inherit', cursor: 'pointer',
            }}
          >
            {yearOptions.map(y => (
              <option key={y} value={y}>{y - 1} / {y} tax year</option>
            ))}
          </select>
          {deductibleTxs.length > 0 && (
            <button className="btn btn-primary btn-sm" onClick={exportCSV}>
              <IDownload size={13}/> Export CSV
            </button>
          )}
        </div>
      </div>

      {/* ── Tax year info bar ── */}
      <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 20, padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 10, border: '1px solid var(--line)' }}>
        📅 Showing deductible expenses from <strong style={{ color: 'var(--ink)' }}>1 March {endYear - 1}</strong> to <strong style={{ color: 'var(--ink)' }}>28 February {endYear}</strong>.
        Mark transactions as tax deductible from the <strong style={{ color: 'var(--ink)' }}>Transactions</strong> page using the Tax column.
      </div>

      {deductibleTxs.length === 0 ? (
        <div className="empty">
          <div className="empty-icon" style={{ fontSize: 32 }}>🧾</div>
          <h3 className="serif" style={{ fontSize: 22 }}>No deductible expenses yet</h3>
          <p>Go to <strong>Transactions</strong> and click the <strong>+ Tax</strong> button on any expense to flag it as tax deductible.</p>
        </div>
      ) : (
        <>
          {/* ── Summary cards by type ── */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 20 }}>
            {/* Total card */}
            <div className="card card-pad fade-up" style={{ flex: '1 1 160px', borderLeft: '3px solid var(--mint)' }}>
              <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', marginBottom: 4 }}>Total deductible</div>
              <div className="serif" style={{ fontSize: 26, letterSpacing: '-0.01em' }}>{fmtZARShort(totalDeductible)}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{deductibleTxs.length} transaction{deductibleTxs.length !== 1 ? 's' : ''}</div>
            </div>

            {DEDUCTIBLE_TYPES.filter(dt => byType[dt.id] > 0).map((dt, i) => (
              <div
                key={dt.id}
                className="card card-pad fade-up"
                style={{ flex: '1 1 140px', borderLeft: `3px solid ${dt.color}`, cursor: 'pointer', animationDelay: `${i * 0.05}s`, outline: typeFilter === dt.id ? `2px solid ${dt.color}` : 'none' }}
                onClick={() => setTypeFilter(f => f === dt.id ? 'all' : dt.id)}
              >
                <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', marginBottom: 4 }}>{dt.label}</div>
                <div className="serif" style={{ fontSize: 22, letterSpacing: '-0.01em' }}>{fmtZARShort(byType[dt.id])}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
                  {((byType[dt.id] / totalDeductible) * 100).toFixed(0)}% of total
                </div>
              </div>
            ))}
          </div>

          {/* ── Type filter tabs ── */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
            <button
              onClick={() => setTypeFilter('all')}
              className={`btn btn-sm ${typeFilter === 'all' ? '' : 'btn-ghost'}`}
            >All</button>
            {DEDUCTIBLE_TYPES.filter(dt => byType[dt.id] > 0).map(dt => (
              <button
                key={dt.id}
                onClick={() => setTypeFilter(f => f === dt.id ? 'all' : dt.id)}
                style={{
                  padding: '5px 12px', borderRadius: 20, fontSize: 12.5, fontWeight: 500,
                  border: `1px solid ${typeFilter === dt.id ? dt.color : 'var(--line)'}`,
                  background: typeFilter === dt.id ? dt.soft : 'none',
                  color: typeFilter === dt.id ? dt.color : 'var(--ink-3)',
                  cursor: 'pointer', transition: 'all 0.15s',
                }}
              >{dt.label}</button>
            ))}
          </div>

          {/* ── Transaction table ── */}
          <div className="card fade-up" style={{ overflow: 'hidden' }}>
            <table className="table">
              <thead>
                <tr>
                  <th>Description</th>
                  <th>Category</th>
                  <th>Type</th>
                  <th>Date</th>
                  <th style={{ textAlign: 'right' }}>Amount</th>
                </tr>
              </thead>
              <tbody>
                {visibleTxs.map((t, i) => {
                  const cat = categoryById(t.category);
                  const dt  = DEDUCTIBLE_TYPES.find(d => d.id === (t.deductibleType || 'other'));
                  return (
                    <tr key={t.id} style={{ animation: `fadeUp 0.3s ${Math.min(i, 12) * 0.025}s both` }}>
                      <td>
                        <div style={{ fontWeight: 500 }}>{t.note || cat?.label || '—'}</div>
                        {(t.tags || []).length > 0 && (
                          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 3 }}>
                            {t.tags.map(tag => (
                              <span key={tag} style={{ fontSize: 11, padding: '1px 6px', borderRadius: 20, background: 'var(--surface-2)', color: 'var(--ink-3)', border: '1px solid var(--line)' }}>#{tag}</span>
                            ))}
                          </div>
                        )}
                      </td>
                      <td>
                        {cat && (
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5 }}>
                            <span className="dot" style={{ background: `var(${cat.cssVar})` }}/>
                            {cat.label}
                          </span>
                        )}
                      </td>
                      <td>
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 5,
                          padding: '2px 8px', borderRadius: 20, fontSize: 11.5, fontWeight: 500,
                          background: dt?.soft, color: dt?.color, border: `1px solid ${dt?.color}`,
                        }}>
                          {dt?.label || 'Other'}
                        </span>
                      </td>
                      <td className="mono" style={{ color: 'var(--ink-3)', fontSize: 12.5 }}>{fmtDate(new Date(t.date))}</td>
                      <td className="mono" style={{ textAlign: 'right', fontWeight: 500 }}>{fmtZAR(t.amount)}</td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr style={{ borderTop: '2px solid var(--line)' }}>
                  <td colSpan={4} style={{ fontWeight: 600, fontSize: 13, paddingTop: 12 }}>
                    {typeFilter === 'all' ? 'Total deductible' : `${DEDUCTIBLE_TYPES.find(d => d.id === typeFilter)?.label} total`}
                  </td>
                  <td className="mono" style={{ textAlign: 'right', fontWeight: 700, fontSize: 15, paddingTop: 12 }}>
                    {fmtZAR(visibleTxs.reduce((s, t) => s + t.amount, 0))}
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>

          {/* ── Disclaimer ── */}
          <div style={{ marginTop: 20, padding: '12px 16px', background: 'var(--surface-2)', borderRadius: 10, border: '1px solid var(--line)', fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.65 }}>
            <strong style={{ color: 'var(--ink-2)' }}>Disclaimer:</strong> This report is for your own record-keeping and is not a SARS-approved tax certificate. Always consult a registered tax practitioner for your submission. Keep original receipts and invoices as supporting documents.
          </div>
        </>
      )}
    </div>
  );
};

Object.assign(window, { PageTax, DEDUCTIBLE_TYPES });
