// History.jsx — list past expenses by month / book / search, with pending filter
const { useState, useEffect, useMemo } = React;

function HistoryScreen({ transactions, books, names, cats, accent, density, pendingOnly, onClearPendingFilter, onSaveAsTemplate, onEdit, onDelete }) {
  const [bookId, setBookId] = useState("all");
  const [month, setMonth] = useState(ym(new Date().toISOString()));
  const [openId, setOpenId] = useState(null);
  const [searchOpen, setSearchOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [preview, setPreview] = useState({ photos: null, index: null });

  // Trip books ignore the month filter — a trip's expenses can span months
  const selectedBook = books.find((b) => b.id === bookId);
  const isTripBook = selectedBook && selectedBook.type === "trip";

  const months = useMemo(() => {
    const set = new Set(transactions.map((t) => ym(t.date)));
    return Array.from(set).sort().reverse();
  }, [transactions]);

  const filtered = useMemo(() => {
    if (pendingOnly) {
      return transactions.filter((t) => t.pending).sort((a, b) => b.date.localeCompare(a.date));
    }
    const q = query.trim().toLowerCase();
    let list = transactions.filter((t) => bookId === "all" ? true : t.bookId === bookId);
    if (!q) {
      list = list.filter((t) => isTripBook ? true : ym(t.date) === month);
    } else {
      list = list.filter((t) => (t.note || "").toLowerCase().includes(q));
    }
    return list.sort((a, b) => b.date.localeCompare(a.date));
  }, [transactions, bookId, month, isTripBook, pendingOnly, query]);

  const groups = useMemo(() => {
    const g = {};
    for (const tx of filtered) {
      const d = ymd(tx.date);
      (g[d] = g[d] || []).push(tx);
    }
    return Object.entries(g);
  }, [filtered]);

  const monthTotal = filtered.
  filter((t) => t.type !== "settle" && !t.pending).
  reduce((s, t) => s + t.amount, 0);

  useEffect(() => {
    if (!isTripBook && months.length > 0 && !months.includes(month)) {
      setMonth(months[0]);
    }
  }, [isTripBook, months]);

  const activeBooks = books.filter((b) => b.status === "active");

  return (
    <div className="screen history" data-screen-label="02 歷史">
      <div className="hist-header">
        {pendingOnly ? (
          <div className="hist-pending-header">
            <span>僅顯示待處理</span>
            <button className="hist-pending-clear" onClick={onClearPendingFilter}>清除</button>
          </div>
        ) : searchOpen ? (
          <div className="hist-search-row">
            <input
              className="hist-search-input"
              placeholder="搜尋備註…"
              value={query}
              autoFocus
              onChange={(e) => setQuery(e.target.value)}
            />
            <button className="hist-search-cancel" onClick={() => { setSearchOpen(false); setQuery(""); }}>取消</button>
          </div>
        ) : (
          <>
            <div className="hist-month-row">
              {isTripBook ? (
                <div className="hist-trip-period num">
                  {selectedBook.startedAt ? ymd(selectedBook.startedAt).replace(/-/g, "/") : "—"}
                  <span className="hist-trip-dash">–</span>
                  {selectedBook.endedAt ? ymd(selectedBook.endedAt).replace(/-/g, "/") : "進行中"}
                </div>
              ) : (
                <select className="hist-month" value={month} onChange={(e) => setMonth(e.target.value)}>
                  {months.map((m) => <option key={m} value={m}>{m.replace("-", " / ")}</option>)}
                </select>
              )}
              <div className="hist-total">
                <span className="hist-total-l">支出</span>
                <span className="hist-total-v num">{fmtMoney(monthTotal)}</span>
              </div>
            </div>
            <div className="hist-tabs">
              <button className={"hist-tab" + (bookId === "all" ? " is-on" : "")} onClick={() => setBookId("all")}>全部</button>
              {activeBooks.map((b) =>
              <button key={b.id}
              className={"hist-tab" + (bookId === b.id ? " is-on" : "")}
              onClick={() => setBookId(b.id)}>{b.name}</button>
              )}
              <button className="hist-search-btn" aria-label="搜尋" onClick={() => setSearchOpen(true)}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="11" cy="11" r="7" />
                  <path d="m20 20-3.5-3.5" />
                </svg>
              </button>
            </div>
          </>
        )}
      </div>

      {groups.length === 0 ?
      <div className="empty">
          <div className="empty-title">這個月沒有紀錄</div>
          <div className="empty-sub">記下第一筆</div>
        </div> :

      <div className="hist-list">
          {groups.map(([d, txs]) => {
          const dayTotal = txs.filter((t) => t.type !== "settle" && !t.pending).reduce((s, t) => s + t.amount, 0);
          return (
            <div key={d} className="hist-day">
                <div className="hist-day-head">
                  <span>{mdLabel(d)}</span>
                  <span className="num">{fmtMoney(dayTotal)}</span>
                </div>
                {txs.map((tx) =>
              <HistoryItem key={tx.id} tx={tx}
              book={books.find((b) => b.id === tx.bookId)}
              names={names} cats={cats} accent={accent} density={density}
              open={openId === tx.id}
              onToggle={() => setOpenId(openId === tx.id ? null : tx.id)}
              onEdit={() => onEdit(tx)}
              onSaveAsTemplate={onSaveAsTemplate}
              onPreviewPhotos={(photos, i) => setPreview({ photos, index: i })}
              onDelete={() => { onDelete(tx); setOpenId(null); }} />
              )}
              </div>);
        })}
        </div>
      }
      <PhotoPreview
        photos={preview.photos}
        index={preview.index}
        onClose={() => setPreview({ photos: null, index: null })}
        onChange={(i) => setPreview((s) => ({ ...s, index: i }))} />
    </div>);
}

function HistoryItem({ tx, book, names, cats, accent, density, open, onToggle, onEdit, onDelete, onSaveAsTemplate, onPreviewPhotos }) {
  if (tx.type === "settle") {
    return (
      <>
        <div className={"hist-item settle" + (open ? " open" : "")} onClick={onToggle}>
          <div className="hist-cat" style={{ color: accent, borderColor: accent }}>結</div>
          <div className="hist-body">
            <div className="hist-l1">結算清零</div>
            <div className="hist-l2">{tx.note} · {hm(tx.date)}</div>
          </div>
          <div className="hist-r num" style={{ color: accent }}>{fmtMoney(tx.amount)}</div>
        </div>
        {open &&
        <div className="hist-actions">
            <button className="danger" onClick={() => { if (confirm("刪除這筆結算？")) onDelete(); }}>刪除結算</button>
          </div>
        }
      </>);
  }
  const cat = cats.find((c) => c.id === tx.category);
  const splitTag =
  tx.split.mode === "even" ? "均分" :
  tx.split.mode === "ratio" ? `${names.A} : ${names.B} / ${tx.split.ratio[0]} : ${tx.split.ratio[1]}` :
  tx.split.mode === "custom" ? `${names.A} ${fmtMoney(tx.split.amounts.A || 0)} / ${names.B} ${fmtMoney(tx.split.amounts.B || 0)}` :
  tx.split.mode === "treat" ? `${names[tx.split.treatBy]} 請客` : null;
  return (
    <>
      <div className={"hist-item" + (density === "compact" ? " compact" : "") + (open ? " open" : "") + (tx.pending ? " pending" : "")}
      style={tx.pending ? { borderLeftColor: accent } : undefined}
      onClick={onToggle}>
        <div className="hist-cat">{cat?.label}</div>
        <div className="hist-body">
          <div className="hist-l1">
            {tx.note || cat?.hint}
            {tx.items && tx.items.length > 0 && <span className="hist-items-tag num">　{tx.items.length}項</span>}
          </div>
          {density !== "compact" &&
          <div className="hist-l2">
              {names[tx.payer]} 付 · {book?.name}
              {splitTag && <> · {splitTag}</>}
            </div>
          }
        </div>
        <div className="hist-r num">
          {tx.pending ? <span className="pending-tag" style={{ color: accent }}>待處理</span> : fmtMoney(tx.amount)}
        </div>
      </div>
      {open && tx.photos && tx.photos.length > 0 &&
      <div className="hist-photos">
          {tx.photos.map((p, i) =>
            <div key={i} className="hist-photo-thumb"
              style={{ backgroundImage: `url(${p})` }}
              onClick={(e) => { e.stopPropagation(); onPreviewPhotos(tx.photos, i); }} />
          )}
        </div>
      }
      {open &&
      <div className="hist-actions hist-actions-3">
          <button onClick={onEdit}>編輯</button>
          <button className="danger" onClick={() => { if (confirm("刪除這筆？")) onDelete(); }}>刪除</button>
          <button onClick={() => {
            const name = prompt("組套名稱", tx.note || "");
            if (name && name.trim()) onSaveAsTemplate(tx, name.trim());
          }}>組套</button>
        </div>
      }
    </>);
}

window.HistoryScreen = HistoryScreen;
