import { useState, useRef, useCallback } from "preact/hooks";
import type { WrapupData, WrapupTodo, WrapupExpense, ActualDay } from "../../lib/types";

function processingStatus(actuals: ActualDay[]): { total: number; plan: number; done: number } {
  let total = 0;
  let plan = 0;
  for (const day of actuals) {
    for (const e of day.entries) {
      total++;
      if (e.tags?.includes("plan")) plan++;
    }
  }
  return { total, plan, done: total - plan };
}

export function WrapupTab({ wrapup, tripId, actuals }: { wrapup: WrapupData; tripId: string; actuals: ActualDay[] }) {
  const [data, setData] = useState<WrapupData>(wrapup);
  const saveTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

  const persist = useCallback((updated: WrapupData) => {
    if (saveTimeout.current) clearTimeout(saveTimeout.current);
    saveTimeout.current = setTimeout(() => {
      fetch(`/travel/api/wrapup?tripId=${tripId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updated),
      }).catch(() => {});
    }, 500);
  }, [tripId]);

  const toggleTodo = (idx: number) => {
    const updated = { ...data, todos: data.todos.map((t, i) => i === idx ? { ...t, done: !t.done } : t) };
    setData(updated);
    persist(updated);
  };

  const stats = processingStatus(actuals);
  const pct = stats.total > 0 ? Math.round((stats.done / stats.total) * 100) : 0;

  return (
    <div class="wrapup-tab">
      <div class="wrapup-section">
        <div class="wrapup-section-title">Processing Status</div>
        <div class="wrapup-progress-bar">
          <div class="wrapup-progress-fill" style={{ width: `${pct}%` }} />
        </div>
        <div class="wrapup-progress-label">{stats.done} of {stats.total} entries recorded ({pct}%) — {stats.plan} still need actuals</div>
      </div>

      <div class="wrapup-section">
        <div class="wrapup-section-title">To Do</div>
        {data.todos.length === 0 && <div class="wrapup-empty">No items</div>}
        {data.todos.map((todo, i) => (
          <label key={i} class={`wrapup-todo ${todo.done ? "done" : ""}`}>
            <input type="checkbox" checked={todo.done} onChange={() => toggleTodo(i)} />
            <span>{todo.task}</span>
          </label>
        ))}
      </div>

      {data.expenses.length > 0 && (
        <div class="wrapup-section">
          <div class="wrapup-section-title">Expenses</div>
          <div class="wrapup-expenses">
            {data.expenses.map((exp, i) => (
              <div key={i} class="wrapup-expense-row">
                <span class="wrapup-expense-item">{exp.item}</span>
                {exp.category && <span class="wrapup-expense-cat">{exp.category}</span>}
                <span class="wrapup-expense-amount">{exp.amount}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {data.highlights.length > 0 && (
        <div class="wrapup-section">
          <div class="wrapup-section-title">Highlights</div>
          {data.highlights.map((h, i) => (
            <div key={i} class="wrapup-highlight">{h}</div>
          ))}
        </div>
      )}

      {data.lessons.length > 0 && (
        <div class="wrapup-section">
          <div class="wrapup-section-title">Lessons</div>
          {data.lessons.map((l, i) => (
            <div key={i} class="wrapup-lesson">{l}</div>
          ))}
        </div>
      )}

      {data.summary && (
        <div class="wrapup-section">
          <div class="wrapup-section-title">Summary</div>
          <div class="wrapup-summary">{data.summary}</div>
        </div>
      )}
    </div>
  );
}
