// Auto-rezerwacja — CRUD zadań
const { useState: uSA, useEffect: uEA, useMemo: uMA } = React;

function AutoTaskForm({ initial, words, onSave, onCancel, saving }) {
  const [form, setForm] = uSA(initial || {
    name: "",
    active: true,
    category: "A",
    exam_type: "praktyka",
    date_from: new Date().toISOString().slice(0, 10),
    date_to: new Date(Date.now() + 45 * 86400_000).toISOString().slice(0, 10),
    check_interval_s: 60,
    word_ids: [],
  });
  const [voivFilter, setVoivFilter] = uSA("");

  const voivs = uMA(() => ["", ...Array.from(new Set(words.map(w => w.voivodeship))).sort()], [words]);
  const wordList = uMA(() =>
    voivFilter ? words.filter(w => w.voivodeship === voivFilter) : words
  , [words, voivFilter]);

  const toggle = (id) => {
    setForm(f => ({
      ...f,
      word_ids: f.word_ids.includes(id)
        ? f.word_ids.filter(x => x !== id)
        : [...f.word_ids, id],
    }));
  };

  const submit = (e) => {
    e.preventDefault();
    onSave(form);
  };

  return (
    <form onSubmit={submit} className="card" style={{ padding: 16, marginBottom: 14 }}>
      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>
        {initial?.id ? "Edytuj zadanie" : "Nowe zadanie auto-rezerwacji"}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="at-grid">
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Nazwa</div>
          <input className="input" value={form.name} onChange={e=>setForm(f=>({...f, name: e.target.value}))} required />
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Aktywne</div>
          <select className="select" value={form.active ? "1" : "0"} onChange={e=>setForm(f=>({...f, active: e.target.value === "1"}))}>
            <option value="1">TAK</option>
            <option value="0">NIE</option>
          </select>
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Kategoria</div>
          <select className="select" value={form.category} onChange={e=>setForm(f=>({...f, category: e.target.value}))}>
            {["A","A1","A2","AM","B","B+E","C","C+E","D","T"].map(c => <option key={c} value={c}>{c}</option>)}
          </select>
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Typ egzaminu</div>
          <select className="select" value={form.exam_type} onChange={e=>setForm(f=>({...f, exam_type: e.target.value}))}>
            <option value="praktyka">Praktyka</option>
            <option value="teoria">Teoria</option>
            <option value="oba">Egzamin łączony</option>
          </select>
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Data od</div>
          <input className="input" type="date" value={form.date_from} onChange={e=>setForm(f=>({...f, date_from: e.target.value}))} required />
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Data do</div>
          <input className="input" type="date" value={form.date_to} onChange={e=>setForm(f=>({...f, date_to: e.target.value}))} required />
        </label>
        <label>
          <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Interwał sprawdzania (s)</div>
          <input className="input mono" type="number" min={30} max={600} value={form.check_interval_s} onChange={e=>setForm(f=>({...f, check_interval_s: Number(e.target.value)}))} />
        </label>
      </div>

      <div style={{ marginTop: 14, marginBottom: 8, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>
          WORDy ({form.word_ids.length} wybranych):
        </div>
        <select className="select" style={{ width: "auto" }} value={voivFilter} onChange={e=>setVoivFilter(e.target.value)}>
          {voivs.map(v => <option key={v} value={v}>{v || "— wszystkie —"}</option>)}
        </select>
      </div>
      <div style={{ maxHeight: 220, overflow: "auto", border: "1px solid var(--border)", borderRadius: 4, marginBottom: 14 }}>
        {wordList.length === 0 && <div style={{padding: 10, color: "var(--fg-muted)", fontSize: 12}}>Brak WORDów — odśwież listę w widoku „Sprawdź"</div>}
        {wordList.map(w => (
          <label key={w.id} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "7px 10px", borderBottom: "1px solid var(--border)",
            cursor: "pointer", fontSize: 13,
          }}>
            <input type="checkbox" checked={form.word_ids.includes(w.id)} onChange={()=>toggle(w.id)} />
            <span style={{
              color: "var(--fg-muted)", fontSize: 11,
              width: 160, flexShrink: 0,
              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
            }} title={w.voivodeship}>{w.voivodeship}</span>
            <span style={{ flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={w.name}>{w.name}</span>
          </label>
        ))}
      </div>

      <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
        <button type="button" className="btn" onClick={onCancel}>Anuluj</button>
        <button type="submit" className="btn primary" disabled={saving || form.word_ids.length === 0}>
          {saving ? "Zapisywanie…" : "Zapisz"}
        </button>
      </div>

      <style>{`@media (max-width: 760px) { .at-grid { grid-template-columns: 1fr !important; } }`}</style>
    </form>
  );
}

function AutoTasksView({ toast }) {
  const [tasks, setTasks] = uSA([]);
  const [words, setWords] = uSA([]);
  const [loading, setLoading] = uSA(true);
  const [editing, setEditing] = uSA(null); // null | "new" | task obj
  const [saving, setSaving] = uSA(false);

  const load = async () => {
    setLoading(true);
    try {
      const [t, w] = await Promise.all([
        window.ZlapApi.listAutoTasks(),
        window.ZlapApi.listWords(),
      ]);
      setTasks(t); setWords(w);
    } catch (e) {
      toast(`Błąd: ${e.message}`, "err");
    } finally {
      setLoading(false);
    }
  };
  uEA(() => { load(); }, []);

  const save = async (form) => {
    setSaving(true);
    try {
      if (editing && editing.id) {
        await window.ZlapApi.updateAutoTask(editing.id, form);
        toast("Zaktualizowano zadanie", "ok");
      } else {
        await window.ZlapApi.createAutoTask(form);
        toast("Utworzono zadanie", "ok");
      }
      setEditing(null);
      await load();
    } catch (e) {
      toast(`Błąd: ${e.message}`, "err");
    } finally {
      setSaving(false);
    }
  };

  const toggleActive = async (task) => {
    try {
      await window.ZlapApi.updateAutoTask(task.id, { active: !task.active });
      await load();
    } catch (e) {
      toast(`Błąd: ${e.message}`, "err");
    }
  };

  const del = async (task) => {
    if (!confirm(`Usunąć zadanie „${task.name}"?`)) return;
    try {
      await window.ZlapApi.deleteAutoTask(task.id);
      toast("Usunięto", "ok");
      await load();
    } catch (e) {
      toast(`Błąd: ${e.message}`, "err");
    }
  };

  const wordName = (id) => words.find(w => w.id === id)?.name || `#${id}`;

  return (
    <div style={{ padding: "18px 22px 80px" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 18, fontWeight: 600 }}>Auto-rezerwacja</div>
          <div style={{ color: "var(--fg-muted)", fontSize: 12, marginTop: 2 }}>
            Bot sprawdza wybrane WORDy co ustalony czas i rezerwuje przy znalezieniu pasującego slota.
          </div>
        </div>
        {editing === null && (
          <button className="btn primary" onClick={() => setEditing("new")}>
            <Icon name="zap" size={12}/> Nowe zadanie
          </button>
        )}
      </div>

      {editing !== null && (
        <AutoTaskForm
          initial={editing === "new" ? null : editing}
          words={words}
          onSave={save}
          onCancel={() => setEditing(null)}
          saving={saving}
        />
      )}

      {loading && <div style={{ color: "var(--fg-muted)" }}>Ładowanie…</div>}
      {!loading && tasks.length === 0 && editing === null && (
        <div className="card" style={{ padding: 20, color: "var(--fg-muted)", textAlign: "center" }}>
          Brak zadań. Utwórz pierwsze klikając „Nowe zadanie".
        </div>
      )}

      <div style={{ display: "grid", gap: 10 }}>
        {tasks.map(t => (
          <div key={t.id} className="card" style={{ padding: 14, display: "flex", alignItems: "flex-start", gap: 12, flexWrap: "wrap" }}>
            <div style={{ flex: "1 1 auto", minWidth: 220 }}>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>
                {t.name} {t.active ? <span className="badge ok" style={{marginLeft: 6}}>aktywne</span> : <span className="badge muted" style={{marginLeft: 6}}>wstrzymane</span>}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>
                kat. {t.category} · {t.exam_type} · {t.date_from} → {t.date_to} · co {t.check_interval_s}s
              </div>
              <div style={{ fontSize: 12, marginTop: 6 }}>
                <span style={{ color: "var(--fg-muted)" }}>WORDy: </span>
                {t.word_ids.map(wordName).join(", ")}
              </div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn ghost" onClick={() => toggleActive(t)}>
                {t.active ? <><Icon name="pause" size={12}/> Wstrzymaj</> : <><Icon name="play" size={12}/> Aktywuj</>}
              </button>
              <button className="btn ghost" onClick={() => setEditing(t)}><Icon name="settings" size={12}/> Edytuj</button>
              <button className="btn ghost" onClick={() => del(t)} style={{color: "var(--err)"}}><Icon name="trash" size={12}/></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.AutoTasksView = AutoTasksView;
