// Receitas and Despesas pages - editable monthly grids matching the spreadsheet structure

const { useState: useStateG, useMemo: useMemoG } = React;

// ---------- YEAR SWITCH ----------
function YearSwitch({ year, onChange, years = [2025, 2026, 2027] }) {
  return (
    <div className="year-switch">
      {years.map(y => (
        <button key={y} className={year === y ? "active" : ""} onClick={() => onChange(y)}>{y}</button>
      ))}
    </div>
  );
}

// ---------- EDITABLE CELL ----------
function EditCell({ value, onChange, dim }) {
  const [editing, setEditing] = useStateG(false);
  const [draft, setDraft] = useStateG("");

  function start() {
    setDraft(value > 0 ? String(value).replace(".", ",") : "");
    setEditing(true);
  }
  function commit() {
    const parsed = window.parseValor(draft);
    onChange(isNaN(parsed) ? 0 : parsed);
    setEditing(false);
  }
  function onKey(e) {
    if (e.key === "Enter") { e.preventDefault(); commit(); e.target.blur(); }
    else if (e.key === "Escape") { setEditing(false); }
    else if (e.key === "Tab") { commit(); /* tab default behavior moves focus */ }
  }

  if (editing) {
    return (
      <input
        className="gc-input"
        autoFocus
        value={draft}
        onChange={e => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={onKey}
      />
    );
  }
  return (
    <button className={`gc-cell ${dim ? "gc-dim" : ""} ${value > 0 ? "gc-has" : ""}`} onClick={start}>
      {value > 0 ? window.fmtBRLString(value).replace("R$ ", "") : <span className="gc-empty">—</span>}
    </button>
  );
}

// ---------- GRID TABLE ----------
function GridTable({ headers, rows, summary, hint }) {
  return (
    <div className="grid-table-wrap">
      <table className="grid-table">
        <thead>
          <tr>
            {headers.map((h, i) => <th key={i} className={i === 0 ? "gh-row" : "gh-month"}>{h}</th>)}
          </tr>
        </thead>
        <tbody>{rows}</tbody>
        {summary && <tfoot>{summary}</tfoot>}
      </table>
      {hint && <div className="grid-hint">{hint}</div>}
    </div>
  );
}

// ---------- RECEITAS PAGE ----------
function ReceitasPage({ aggregates, txs, year, onUpdate, onChangeYear }) {
  const data = (aggregates[year] || aggregates[2026] || { receitas: {}, despesas: { cards: {}, fixos: {} } });
  const sources = Object.keys(data.receitas);
  const [newSource, setNewSource] = useStateG("");

  // Add detailed transactions per source per month for context
  const txBySourceMonth = useMemoG(() => {
    const map = {};
    for (const t of txs) {
      if (t.type !== "Receita" || !t.date.startsWith(String(year))) continue;
      const m = Number(t.date.slice(5, 7)) - 1;
      const key = `${t.description.split(" — ")[0]}|${m}`;
      map[key] = (map[key] || 0) + Number(t.amount || 0);
    }
    return map;
  }, [txs, year]);

  function setCell(src, monthIdx, val) {
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const arr = aggs[year].receitas[src].slice();
      arr[monthIdx] = val;
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], receitas: { ...aggs[year].receitas, [src]: arr } } }
      };
    });
  }

  function addSource() {
    const name = newSource.trim();
    if (!name || data.receitas[name]) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], receitas: { ...aggs[year].receitas, [name]: new Array(12).fill(0) } } }
      };
    });
    setNewSource("");
  }
  function delSource(src) {
    if (!confirm(`Remover linha "${src}"?`)) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const { [src]: _, ...rest } = aggs[year].receitas;
      return { ...prev, aggregates: { ...aggs, [year]: { ...aggs[year], receitas: rest } } };
    });
  }

  const monthTotals = new Array(12).fill(0);
  const sourceTotals = {};
  for (const src of sources) {
    sourceTotals[src] = 0;
    for (let m = 0; m < 12; m++) {
      const v = data.receitas[src][m] || 0;
      monthTotals[m] += v;
      sourceTotals[src] += v;
    }
  }
  const grandTotal = monthTotals.reduce((s, v) => s + v, 0);

  const headers = ["Origem", ...window.MESES, "Total"];

  const rows = sources.map(src => (
    <tr key={src}>
      <td className="gt-row-name">
        <span>{src}</span>
        <button className="gt-row-del" onClick={() => delSource(src)} title="Excluir linha">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a1 1 0 011-1h6a1 1 0 011 1v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
        </button>
      </td>
      {window.MESES.map((_, m) => (
        <td key={m} className="gt-month-cell">
          <EditCell value={data.receitas[src][m] || 0} onChange={(v) => setCell(src, m, v)}/>
          {txBySourceMonth[`${src}|${m}`] > 0 && (
            <span className="gt-detail" title="Inclui lançamentos detalhados">+ R$ {txBySourceMonth[`${src}|${m}`].toFixed(0)}</span>
          )}
        </td>
      ))}
      <td className="gt-row-total">{window.fmtBRLString(sourceTotals[src]).replace("R$ ", "")}</td>
    </tr>
  ));

  const summary = (
    <tr className="gt-total-row">
      <td className="gt-row-name">Total</td>
      {monthTotals.map((v, i) => (
        <td key={i} className="gt-month-cell">{v > 0 ? window.fmtBRLString(v).replace("R$ ", "") : "—"}</td>
      ))}
      <td className="gt-row-total grand">{window.fmtBRLString(grandTotal).replace("R$ ", "")}</td>
    </tr>
  );

  return (
    <div className="page">
      <div className="page-head">
        <h2>💰 Receitas</h2>
        <div className="page-head-actions">
          <YearSwitch year={year} onChange={onChangeYear}/>
          <span className="page-hint">Clique numa célula para editar</span>
        </div>
      </div>
      <div className="card grid-card">
        <div className="card-head">
          <h3>Receitas {year}</h3>
          <span className="big-total">Total do ano: <strong>{window.fmtBRLString(grandTotal)}</strong></span>
        </div>
        <GridTable headers={headers} rows={rows} summary={summary}/>
        <div className="grid-add">
          <input
            placeholder="Adicionar nova origem (ex: Aluguel recebido)"
            value={newSource}
            onChange={e => setNewSource(e.target.value)}
            onKeyDown={e => e.key === "Enter" && addSource()}
          />
          <button className="btn-green" onClick={addSource} disabled={!newSource.trim()}>+ Adicionar Origem</button>
        </div>
      </div>
    </div>
  );
}

// ---------- DESPESAS PAGE ----------
function DespesasPage({ aggregates, year, onUpdate, onChangeYear }) {
  const data = (aggregates[year] || aggregates[2026] || { receitas: {}, despesas: { cards: {}, fixos: {} } });
  const cards = Object.keys(data.despesas.cards);
  const fixos = Object.keys(data.despesas.fixos);
  const [newCard, setNewCard] = useStateG("");
  const [newFixo, setNewFixo] = useStateG("");

  function setCardCell(card, pessoa, m, v) {
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const arr = aggs[year].despesas.cards[card][pessoa].slice();
      arr[m] = v;
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, cards: { ...aggs[year].despesas.cards, [card]: { ...aggs[year].despesas.cards[card], [pessoa]: arr } } } } }
      };
    });
  }
  function setFixoCell(name, m, v) {
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const arr = aggs[year].despesas.fixos[name].slice();
      arr[m] = v;
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, fixos: { ...aggs[year].despesas.fixos, [name]: arr } } } }
      };
    });
  }
  function addCard() {
    const name = newCard.trim();
    if (!name || data.despesas.cards[name]) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, cards: { ...aggs[year].despesas.cards, [name]: { Lucas: new Array(12).fill(0), Larissa: new Array(12).fill(0) } } } } }
      };
    });
    setNewCard("");
  }
  function delCard(card) {
    if (!confirm(`Remover cartão "${card}"?`)) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const { [card]: _, ...rest } = aggs[year].despesas.cards;
      return { ...prev, aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, cards: rest } } } };
    });
  }
  function addFixo() {
    const name = newFixo.trim();
    if (!name || data.despesas.fixos[name]) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      return {
        ...prev,
        aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, fixos: { ...aggs[year].despesas.fixos, [name]: new Array(12).fill(0) } } } }
      };
    });
    setNewFixo("");
  }
  function delFixo(name) {
    if (!confirm(`Remover linha "${name}"?`)) return;
    onUpdate(prev => {
      const aggs = window.ensureYear(prev.aggregates, year);
      const { [name]: _, ...rest } = aggs[year].despesas.fixos;
      return { ...prev, aggregates: { ...aggs, [year]: { ...aggs[year], despesas: { ...aggs[year].despesas, fixos: rest } } } };
    });
  }

  // monthly grand totals
  const monthTotals = new Array(12).fill(0);
  for (const card of cards) {
    for (const pessoa of Object.keys(data.despesas.cards[card])) {
      for (let m = 0; m < 12; m++) monthTotals[m] += data.despesas.cards[card][pessoa][m] || 0;
    }
  }
  for (const name of fixos) {
    for (let m = 0; m < 12; m++) monthTotals[m] += data.despesas.fixos[name][m] || 0;
  }
  const grandTotal = monthTotals.reduce((s, v) => s + v, 0);

  const headers = ["", ...window.MESES, "Total"];

  // Build rows: per card, Lucas/Larissa/Total; then a section of fixos
  const cardRows = [];
  for (const card of cards) {
    const pessoas = Object.keys(data.despesas.cards[card]);
    const cardTotalByMonth = new Array(12).fill(0);
    let cardTotalAll = 0;
    cardRows.push(
      <tr key={`${card}-header`} className="gt-section">
        <td className="gt-row-name gt-section-name" colSpan={1}>
          <strong>💳 {card}</strong>
          <button className="gt-row-del" onClick={() => delCard(card)} title="Excluir cartão">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a1 1 0 011-1h6a1 1 0 011 1v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
          </button>
        </td>
        <td colSpan={13}></td>
      </tr>
    );
    for (const pessoa of pessoas) {
      let total = 0;
      cardRows.push(
        <tr key={`${card}-${pessoa}`}>
          <td className="gt-row-name gt-sub">{pessoa}</td>
          {window.MESES.map((_, m) => {
            const v = data.despesas.cards[card][pessoa][m] || 0;
            total += v;
            cardTotalByMonth[m] += v;
            return (
              <td key={m} className="gt-month-cell">
                <EditCell value={v} onChange={(nv) => setCardCell(card, pessoa, m, nv)}/>
              </td>
            );
          })}
          <td className="gt-row-total">{total > 0 ? window.fmtBRLString(total).replace("R$ ", "") : "—"}</td>
        </tr>
      );
      cardTotalAll += total;
    }
    cardRows.push(
      <tr key={`${card}-total`} className="gt-subtotal">
        <td className="gt-row-name gt-sub"><em>Total {card}</em></td>
        {cardTotalByMonth.map((v, m) => (
          <td key={m} className="gt-month-cell">{v > 0 ? window.fmtBRLString(v).replace("R$ ", "") : "—"}</td>
        ))}
        <td className="gt-row-total">{window.fmtBRLString(cardTotalAll).replace("R$ ", "")}</td>
      </tr>
    );
  }

  // Fixos rows
  const fixoRows = [];
  if (fixos.length > 0) {
    fixoRows.push(
      <tr key="fixos-header" className="gt-section">
        <td className="gt-row-name gt-section-name" colSpan={14}><strong>📌 Despesas Fixas</strong></td>
      </tr>
    );
    for (const name of fixos) {
      let total = 0;
      fixoRows.push(
        <tr key={name}>
          <td className="gt-row-name gt-sub">
            <span>{name}</span>
            <button className="gt-row-del" onClick={() => delFixo(name)} title="Excluir">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a1 1 0 011-1h6a1 1 0 011 1v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
            </button>
          </td>
          {window.MESES.map((_, m) => {
            const v = data.despesas.fixos[name][m] || 0;
            total += v;
            return (
              <td key={m} className="gt-month-cell">
                <EditCell value={v} onChange={(nv) => setFixoCell(name, m, nv)}/>
              </td>
            );
          })}
          <td className="gt-row-total">{total > 0 ? window.fmtBRLString(total).replace("R$ ", "") : "—"}</td>
        </tr>
      );
    }
  }

  const summary = (
    <tr className="gt-total-row">
      <td className="gt-row-name">Total Geral</td>
      {monthTotals.map((v, i) => (
        <td key={i} className="gt-month-cell">{v > 0 ? window.fmtBRLString(v).replace("R$ ", "") : "—"}</td>
      ))}
      <td className="gt-row-total grand">{window.fmtBRLString(grandTotal).replace("R$ ", "")}</td>
    </tr>
  );

  return (
    <div className="page">
      <div className="page-head">
        <h2>💸 Despesas</h2>
        <div className="page-head-actions">
          <YearSwitch year={year} onChange={onChangeYear}/>
          <span className="page-hint">Clique numa célula para editar</span>
        </div>
      </div>
      <div className="card grid-card">
        <div className="card-head">
          <h3>Despesas {year}</h3>
          <span className="big-total">Total do ano: <strong>{window.fmtBRLString(grandTotal)}</strong></span>
        </div>
        <GridTable headers={headers} rows={[...cardRows, ...fixoRows]} summary={summary}/>
        <div className="grid-add-row">
          <div className="grid-add">
            <input
              placeholder="Novo cartão (ex: Nubank)"
              value={newCard}
              onChange={e => setNewCard(e.target.value)}
              onKeyDown={e => e.key === "Enter" && addCard()}
            />
            <button className="btn-green" onClick={addCard} disabled={!newCard.trim()}>+ Cartão</button>
          </div>
          <div className="grid-add">
            <input
              placeholder="Nova despesa fixa (ex: Aluguel)"
              value={newFixo}
              onChange={e => setNewFixo(e.target.value)}
              onKeyDown={e => e.key === "Enter" && addFixo()}
            />
            <button className="btn-green" onClick={addFixo} disabled={!newFixo.trim()}>+ Despesa Fixa</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReceitasPage, DespesasPage });
