// Tryb "Sprawdź teraz" — manual skan wybranych WORDów, opcjonalna rezerwacja
const { useState: uSC, useEffect: uEC, useMemo: uMC } = React;

function CheckNowView({ toast }) {
  const [words, setWords] = uSC([]);
  const [wordsLoading, setWordsLoading] = uSC(true);
  const [selectedWords, setSelectedWords] = uSC(new Set());
  const [selectedVoiv, setSelectedVoiv] = uSC("");
  const [category, setCategory] = uSC("A");
  const [examType, setExamType] = uSC("praktyka");

  const [runId, setRunId] = uSC(null);
  const [run, setRun] = uSC(null);
  const [reservingId, setReservingId] = uSC("");

  uEC(() => {
    window.ZlapApi.listWords()
      .then(setWords)
      .catch(e => toast(`Błąd listy WORDów: ${e.message}`, "err"))
      .finally(() => setWordsLoading(false));
  }, []);

  uEC(() => {
    if (!runId) return;
    let cancelled = false;
    const tick = async () => {
      try {
        const r = await window.ZlapApi.getCheckRun(runId);
        if (!cancelled) {
          setRun(r);
          if (r.status === "done" || r.status === "failed") return;
        }
      } catch (e) {}
      if (!cancelled) setTimeout(tick, 2000);
    };
    tick();
    return () => { cancelled = true; };
  }, [runId]);

  const voivodeships = uMC(() => {
    const s = new Set(words.map(w => w.voivodeship));
    return ["", ...Array.from(s).sort()];
  }, [words]);

  const wordsInVoiv = uMC(() => {
    return selectedVoiv ? words.filter(w => w.voivodeship === selectedVoiv) : words;
  }, [words, selectedVoiv]);

  const toggleWord = (id) => {
    setSelectedWords(s => {
      const ns = new Set(s);
      if (ns.has(id)) ns.delete(id); else ns.add(id);
      return ns;
    });
  };
  const selectAll = () => setSelectedWords(new Set(wordsInVoiv.map(w => w.id)));
  const clearAll = () => setSelectedWords(new Set());

  const refreshWords = async () => {
    try {
      toast("Odświeżam listę WORDów — to może potrwać kilkanaście sekund…", "info");
      const r = await window.ZlapApi.refreshWords();
      const fresh = await window.ZlapApi.listWords();
      setWords(fresh);
      toast(`Zaktualizowano: +${r.inserted} nowych, ${r.updated} odświeżonych`, "ok");
    } catch (e) {
      toast(`Błąd refresh: ${e.message}`, "err");
    }
  };

  const runCheck = async () => {
    if (selectedWords.size === 0) {
      toast("Wybierz co najmniej jeden WORD", "warn");
      return;
    }
    try {
      const r = await window.ZlapApi.checkNow({
        word_ids: Array.from(selectedWords),
        category,
        exam_type: examType,
      });
      setRunId(r.id);
      setRun(null);
      toast("Skan uruchomiony — czekaj na wyniki", "info");
    } catch (e) {
      toast(`Błąd: ${e.message}`, "err");
    }
  };

  const reserve = async (row) => {
    if (!confirm(
      `Zarezerwować ${row.word_name} ${row.slot_date} ${row.slot_time}?\n\n` +
      `Bot przejdzie cały flow, wypełni dane kandydata i wyśle link do płatności na email.\n` +
      `MASZ 3 MINUTY na opłacenie po otrzymaniu linku.`
    )) return;
    setReservingId(`${row.word_id}-${row.slot_date}-${row.slot_time}`);
    try {
      const res = await window.ZlapApi.reserveFromCheck(runId, {
        word_id: row.word_id,
        slot_date: row.slot_date,
        slot_time: row.slot_time,
        category,
        exam_type: examType,
      });
      if (res.status === "reserved") {
        toast(`ZAREZERWOWANO — link do płatności wysłany na email. Masz 3 minuty!`, "hit");
      } else {
        toast(`Status: ${res.status} — ${res.error || "sprawdź Rezerwacje"}`, "warn");
      }
    } catch (e) {
      toast(`Błąd rezerwacji: ${e.message}`, "err");
    } finally {
      setReservingId("");
    }
  };

  return (
    <div style={{ padding: "18px 22px 80px" }}>
      <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 4 }}>Sprawdź terminy</div>
      <div style={{ color: "var(--fg-muted)", fontSize: 12, marginBottom: 16 }}>
        Manualny skan wybranych WORDów. Po kliknięciu „Zarezerwuj" bot przejdzie flow i wyśle link do płatności na email.
      </div>

      <div className="card" style={{ padding: 16, marginBottom: 14 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginBottom: 12 }} className="cn-grid">
          <label>
            <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Województwo</div>
            <select className="select" value={selectedVoiv} onChange={e=>setSelectedVoiv(e.target.value)}>
              {voivodeships.map(v => <option key={v} value={v}>{v || "— wszystkie —"}</option>)}
            </select>
          </label>
          <label>
            <div style={{ fontSize: 12, color: "var(--fg-muted)", marginBottom: 4 }}>Kategoria</div>
            <select className="select" value={category} onChange={e=>setCategory(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={examType} onChange={e=>setExamType(e.target.value)}>
              <option value="praktyka">Praktyka</option>
              <option value="teoria">Teoria</option>
              <option value="oba">Egzamin łączony</option>
            </select>
          </label>
        </div>

        <div style={{ marginBottom: 8, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>
            WORDy do sprawdzenia: <span className="mono">{selectedWords.size}</span> / {wordsInVoiv.length}
          </div>
          <button className="btn ghost" onClick={selectAll}>Zaznacz wszystkie</button>
          <button className="btn ghost" onClick={clearAll}>Wyczyść</button>
          <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
            <button className="btn ghost" onClick={refreshWords}><Icon name="restart" size={12}/> Odśwież listę WORDów</button>
            <button className="btn primary" onClick={runCheck} disabled={selectedWords.size === 0}>
              <Icon name="search" size={12}/> Sprawdź teraz
            </button>
          </div>
        </div>

        {wordsLoading ? (
          <div style={{ color: "var(--fg-muted)", fontSize: 12 }}>Ładowanie listy…</div>
        ) : wordsInVoiv.length === 0 ? (
          <div style={{ color: "var(--fg-muted)", fontSize: 12 }}>
            Brak WORDów w bazie. Kliknij „Odśwież listę WORDów", żeby pobrać z info-car.pl.
          </div>
        ) : (
          <div style={{ maxHeight: 280, overflow: "auto", border: "1px solid var(--border)", borderRadius: 4 }}>
            {wordsInVoiv.map(w => (
              <label key={w.id} style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "8px 10px", borderBottom: "1px solid var(--border)",
                cursor: "pointer", fontSize: 13,
              }}>
                <input type="checkbox" checked={selectedWords.has(w.id)} onChange={()=>toggleWord(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>
                {w.address && <span style={{ color: "var(--fg-dim)", fontSize: 11, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 240 }} title={w.address}>{w.address}</span>}
              </label>
            ))}
          </div>
        )}
      </div>

      {run && (
        <div className="card" style={{ padding: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Wyniki skanu</div>
            <span className={cls("badge", run.status === "done" ? "ok" : run.status === "failed" ? "err" : "info")}>
              {run.status}
            </span>
            {run.status === "running" && (
              <span style={{ color: "var(--fg-muted)", fontSize: 12 }}>Skanowanie w toku…</span>
            )}
          </div>
          {run.error && (
            <div style={{ color: "var(--err)", fontSize: 12, marginBottom: 8 }}>
              <Icon name="alert" size={12}/> {run.error}
            </div>
          )}
          <table className="table">
            <thead>
              <tr><th>Województwo</th><th>WORD</th><th>Najbliższy</th><th>Info</th><th></th></tr>
            </thead>
            <tbody>
              {run.results.length === 0 && <tr><td colSpan={5} style={{padding: 14, color: "var(--fg-muted)"}}>Brak wyników (jeszcze)…</td></tr>}
              {run.results.map((r, i) => (
                <tr key={i}>
                  <td style={{ fontSize: 11, color: "var(--fg-muted)" }}>{r.voivodeship}</td>
                  <td>{r.word_name}</td>
                  <td className="mono">
                    {r.available ? `${r.slot_date} ${r.slot_time}` : "—"}
                  </td>
                  <td style={{ fontSize: 11, color: "var(--fg-muted)" }}>{r.message}</td>
                  <td>
                    {r.available && (
                      <button
                        className="btn primary"
                        disabled={reservingId === `${r.word_id}-${r.slot_date}-${r.slot_time}`}
                        onClick={() => reserve(r)}
                      >
                        {reservingId === `${r.word_id}-${r.slot_date}-${r.slot_time}` ? "Rezerwuję…" : "Zarezerwuj"}
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <style>{`@media (max-width: 760px) { .cn-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}
window.CheckNowView = CheckNowView;
