// Tasks view: filters by date, status, priority, kind. Group by date.

function FilterButton({ label, active, onClick, color }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: "8px 14px", minHeight: 36, borderRadius: 999, fontSize: 13, fontWeight: 500,
        background: active ? (color || "var(--terracotta)") : "var(--surface)",
        color: active ? "#FFF8F0" : "var(--ink-2)",
        border: `1px solid ${active ? (color || "var(--terracotta-2)") : "var(--line)"}`,
        transition: "all .15s ease",
      }}
    >{label}</button>
  );
}

function TasksView({ items, openForm, onStatusChange, onEdit }) {
  const [search, setSearch] = React.useState("");
  const [statusFilter, setStatusFilter] = React.useState(new Set()); // empty = all
  const [priorityFilter, setPriorityFilter] = React.useState(new Set());
  const [kindFilter, setKindFilter] = React.useState(new Set());
  const [dateFilter, setDateFilter] = React.useState("upcoming"); // today | upcoming | week | overdue | all
  const [assigneeFilter, setAssigneeFilter] = React.useState(null); // null = tous, "baptiste" | "imelda"

  const toggle = (set, key, setter) => {
    const ns = new Set(set);
    if (ns.has(key)) ns.delete(key); else ns.add(key);
    setter(ns);
  };

  // Build occurrences for a window of days
  const today = TODAY;
  const range = (() => {
    if (dateFilter === "today")    return [today, today];
    if (dateFilter === "week")     return [today, addDays(today, 6)];
    if (dateFilter === "upcoming") return [today, addDays(today, 30)];
    if (dateFilter === "overdue")  return [addDays(today, -60), addDays(today, -1)];
    return [addDays(today, -60), addDays(today, 60)];
  })();

  const occurrences = [];
  let d = new Date(range[0]);
  while (d <= range[1]) {
    const its = itemsOnDate(items, d);
    its.forEach(it => occurrences.push({ item: it, date: new Date(d) }));
    d = addDays(d, 1);
  }

  // Filter
  const filtered = occurrences.filter(({ item, date }) => {
    if (search && !item.title.toLowerCase().includes(search.toLowerCase())) return false;
    if (kindFilter.size > 0 && !kindFilter.has(item.kind)) return false;
    if (priorityFilter.size > 0 && !priorityFilter.has(item.priority)) return false;
    if (assigneeFilter) {
      if (item.assignee && item.assignee !== assigneeFilter) return false;
    }
    if (statusFilter.size > 0) {
      if (item.kind !== "task") return false;
      const s = statusOn(item, date);
      if (!statusFilter.has(s)) return false;
    }
    if (dateFilter === "overdue") {
      if (item.kind !== "task") return false;
      if ((item.recurrence?.kind || "none") !== "none") return false;
      const s = statusOn(item, date);
      if (["done", "cancelled"].includes(s)) return false;
    }
    return true;
  });

  // Group by date
  const groups = {};
  filtered.forEach(({ item, date }) => {
    const k = ymd(date);
    if (!groups[k]) groups[k] = { date, items: [] };
    groups[k].items.push(item);
  });
  const groupKeys = Object.keys(groups).sort();

  const totalActive = statusFilter.size + priorityFilter.size + kindFilter.size + (search ? 1 : 0) + (assigneeFilter ? 1 : 0);

  return (
    <div className="col gap-5 view-pad" style={{ maxWidth: 1280, margin: "0 auto" }}>
      <SectionHeading
        eyebrow="Toutes les tâches"
        title="Liste"
        count={filtered.length}
        action={<Button variant="primary" icon="plus" onClick={() => openForm()}>Nouvelle tâche</Button>}
      />

      {/* Search + date scope */}
      <Card padding={16}>
        <div className="col gap-3">
          <div className="row gap-3" style={{ flexWrap: "wrap" }}>
            <div className="row gap-2" style={{
              flex: "1 1 280px", minWidth: 240, padding: "8px 12px",
              background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 10,
            }}>
              <Icon name="search" size={14} color="var(--ink-3)" />
              <input
                value={search} onChange={(e) => setSearch(e.target.value)}
                placeholder="Rechercher une tâche, un événement…"
                style={{ flex: 1, border: 0, outline: "none", background: "transparent", fontSize: 16 }} />
              {search && <button onClick={() => setSearch("")} style={{ color: "var(--ink-3)", fontSize: 13, padding: "4px 6px" }}>effacer</button>}
            </div>
            <div className="date-scope-bar row gap-1" style={{ background: "var(--bg-2)", padding: 4, borderRadius: 10, border: "1px solid var(--line)" }}>
              {[
                ["today", "Aujourd'hui"],
                ["week", "Semaine"],
                ["upcoming", "À venir"],
                ["overdue", "En retard"],
                ["all", "Tout"],
              ].map(([k, l]) => (
                <button key={k} onClick={() => setDateFilter(k)} style={{
                  padding: "8px 12px", minHeight: 36, borderRadius: 8, fontSize: 13, fontWeight: 500,
                  background: dateFilter === k ? "var(--surface)" : "transparent",
                  color: dateFilter === k ? "var(--ink)" : "var(--ink-3)",
                  boxShadow: dateFilter === k ? "var(--shadow-sm)" : "none",
                }}>{l}</button>
              ))}
            </div>
          </div>

          <div className="row gap-3" style={{ flexWrap: "wrap", alignItems: "center" }}>
            <div className="tiny" style={{ marginRight: 4 }}>État</div>
            {Object.entries(STATES).map(([k, s]) => (
              <FilterButton key={k} label={s.label} color={s.color}
                active={statusFilter.has(k)}
                onClick={() => toggle(statusFilter, k, setStatusFilter)} />
            ))}
            <div style={{ width: 1, height: 18, background: "var(--line)" }} />
            <div className="tiny" style={{ marginRight: 4 }}>Priorité</div>
            {Object.entries(PRIORITIES).map(([k, p]) => (
              <FilterButton key={k} label={p.label} color={p.color}
                active={priorityFilter.has(k)}
                onClick={() => toggle(priorityFilter, k, setPriorityFilter)} />
            ))}
            <div style={{ width: 1, height: 18, background: "var(--line)" }} />
            <div className="tiny" style={{ marginRight: 4 }}>Assigné</div>
            {Object.entries(USERS).map(([k, u]) => (
              <FilterButton key={k} label={u.name} color={u.color}
                active={assigneeFilter === k}
                onClick={() => setAssigneeFilter(assigneeFilter === k ? null : k)} />
            ))}
            <div style={{ width: 1, height: 18, background: "var(--line)" }} />
            <div className="tiny" style={{ marginRight: 4 }}>Type</div>
            {Object.entries(KINDS).map(([k, kk]) => (
              <FilterButton key={k} label={kk.label} color={kk.color}
                active={kindFilter.has(k)}
                onClick={() => toggle(kindFilter, k, setKindFilter)} />
            ))}
            {totalActive > 0 && (
              <button
                onClick={() => { setStatusFilter(new Set()); setPriorityFilter(new Set()); setKindFilter(new Set()); setSearch(""); setAssigneeFilter(null); }}
                style={{ marginLeft: "auto", color: "var(--terracotta-2)", fontSize: 13, fontWeight: 500, minHeight: 36, padding: "0 8px" }}
              >Réinitialiser</button>
            )}
          </div>
        </div>
      </Card>

      {/* Groups */}
      {groupKeys.length === 0 ? (
        <Empty title="Rien à afficher" hint="Ajustez les filtres ou créez une nouvelle tâche."
          action={<Button variant="primary" icon="plus" onClick={() => openForm()}>Nouvelle tâche</Button>} />
      ) : (
        groupKeys.map(k => {
          const { date, items: its } = groups[k];
          const isToday = sameDay(date, TODAY);
          return (
            <div key={k} className="col gap-2">
              <div className="row gap-3" style={{ alignItems: "baseline" }}>
                <div style={{
                  fontFamily: "var(--font-display)",
                  fontSize: 22, color: isToday ? "var(--terracotta-2)" : "var(--ink)",
                }}>
                  {DAYS_LONG[date.getDay()].charAt(0).toUpperCase() + DAYS_LONG[date.getDay()].slice(1)}{" "}
                  {date.getDate()} <span style={{ color: "var(--ink-3)", fontSize: 16 }}>{MONTHS[date.getMonth()]}</span>
                </div>
                <span className="tiny">{fmtRel(date)}</span>
                <span className="muted small">{its.length} élément{its.length > 1 ? "s" : ""}</span>
              </div>
              <div className="col gap-2">
                {its.map(it => <TaskRow key={it.id + k} item={it} date={date} onStatusChange={onStatusChange} onEdit={onEdit} />)}
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}

Object.assign(window, { TasksView, FilterButton });
