import { useState, useCallback, useRef } from "preact/hooks";
import { slugify } from "../../lib/categories";

export function PackTab({ items, initialState, tripId }: {
  items: string[];
  initialState: Record<string, boolean>;
  tripId: string;
}) {
  const [checked, setChecked] = useState<Record<string, boolean>>(() => {
    const state: Record<string, boolean> = {};
    items.forEach(item => {
      const key = slugify(item);
      state[key] = initialState[key] ?? false;
    });
    return state;
  });

  const saveTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

  const persist = useCallback((newState: Record<string, boolean>) => {
    if (saveTimeout.current) clearTimeout(saveTimeout.current);
    saveTimeout.current = setTimeout(() => {
      fetch(`/travel/api/pack-state?tripId=${tripId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newState),
      }).catch(() => { /* silent fail */ });
    }, 500);
  }, [tripId]);

  const toggle = useCallback((item: string) => {
    const key = slugify(item);
    setChecked(prev => {
      const next = { ...prev, [key]: !prev[key] };
      persist(next);
      return next;
    });
  }, [persist]);

  const total = items.length;
  const done = Object.values(checked).filter(Boolean).length;
  const pct = total > 0 ? Math.round((done / total) * 100) : 0;

  return (
    <div class="pack-tab">
      <div class="pack-header-row">
        <h2 class="pack-heading">Packing List</h2>
        <span class="pack-counter">{done}/{total}</span>
      </div>
      <div class="pack-sub">Tap to check off. Saved automatically.</div>

      <div class="pack-progress">
        <div class="pack-progress-bar" style={{ width: `${pct}%` }} />
      </div>

      <div class="pack-items">
        {items.map(item => {
          const key = slugify(item);
          const isChecked = checked[key] ?? false;
          return (
            <div
              key={key}
              class={`pack-item ${isChecked ? "checked" : ""}`}
              onClick={() => toggle(item)}
            >
              <div class="pack-check">
                <span class="pack-check-mark">{isChecked ? "\u2713" : ""}</span>
              </div>
              <span class="pack-label">{item}</span>
            </div>
          );
        })}
      </div>

      {items.length === 0 && (
        <div class="empty-state">No items in packing list.</div>
      )}
    </div>
  );
}
