import { useEffect, useMemo, useRef, useState } from "preact/hooks";
import "../../styles/jambox-search.css";

export default function JamboxChannelsSearch() {
  const [q, setQ] = useState("");
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");

  // ✅ koszyk kanałów
  const [wanted, setWanted] = useState([]); // [{ name, logo_url, packages:[{id,name}], thematic_packages:[{tid,name}] }]

  const abortRef = useRef(null);

  useEffect(() => {
    const qq = q.trim();
    setErr("");

    if (qq.length === 0) {
      setItems([]);
      setLoading(false);
      return;
    }

    const t = setTimeout(async () => {
      try {
        if (abortRef.current) abortRef.current.abort();
        const ac = new AbortController();
        abortRef.current = ac;

        setLoading(true);

        const params = new URLSearchParams();
        params.set("q", qq);
        params.set("limit", "80");

        const res = await fetch(
          `/api/jambox/jambox-channels-search?${params.toString()}`,
          {
            signal: ac.signal,
            headers: { Accept: "application/json" },
          }
        );

        const json = await res.json();
        if (!res.ok || !json.ok) throw new Error(json?.error || "API_ERROR");

        setItems(Array.isArray(json.data) ? json.data : []);
      } catch (e) {
        if (e?.name !== "AbortError") {
          console.error("jambox-channels-search:", e);
          setErr("Błąd wyszukiwania.");
        }
      } finally {
        setLoading(false);
      }
    }, 250);

    return () => clearTimeout(t);
  }, [q]);

  const meta = useMemo(() => {
    const qq = q.trim();
    if (qq.length === 0) return "";
    if (loading) return "Szukam…";
    if (err) return err;
    return `Znaleziono: ${items.length}`;
  }, [q, loading, err, items]);

  function scrollToPackage(packageName) {
    const key = String(packageName || "").trim();
    if (!key) return;

    const el = document.getElementById(`pkg-${key}`);
    if (!el) {
      console.warn("❌ Nie znaleziono pakietu w DOM:", `pkg-${key}`);
      return;
    }

    el.scrollIntoView({ behavior: "smooth", block: "start" });
    el.classList.add("is-target");
    window.setTimeout(() => el.classList.remove("is-target"), 5400);
  }

  // ==========================
  // ✅ koszyk: dodaj/usuń kanał
  // ==========================
  const isWanted = (c) =>
    wanted.some(
      (w) =>
        String(w.name || "").toLowerCase() === String(c.name || "").toLowerCase()
    );

  function addWanted(c) {
    setWanted((prev) => {
      const exists = prev.some(
        (w) =>
          String(w.name || "").toLowerCase() === String(c.name || "").toLowerCase()
      );
      if (exists) return prev;

      return [
        ...prev,
        {
          name: c.name,
          logo_url: c.logo_url || "",
          packages: Array.isArray(c.packages) ? c.packages : [],
          thematic_packages: Array.isArray(c.thematic_packages)
            ? c.thematic_packages
            : [],
        },
      ];
    });
  }

  function removeWantedByName(name) {
    setWanted((prev) =>
      prev.filter(
        (w) =>
          String(w.name || "").toLowerCase() !== String(name || "").toLowerCase()
      )
    );
  }

  function clearWanted() {
    setWanted([]);
  }

  // =========================================
  // ✅ sugestie pakietów dla koszyka
  //    - GŁÓWNE: exact/ranked (z count)
  //    - TEMATYCZNE: dodatki do dokupienia (bez liczenia)
  // =========================================
  const packageSuggestions = useMemo(() => {
    if (!wanted.length) return { exact: [], ranked: [], thematic: [] };

    // ======= GŁÓWNE =======
    const counts = new Map(); // key = packageName
    for (const ch of wanted) {
      const pkgs = Array.isArray(ch.packages) ? ch.packages : [];
      for (const p of pkgs) {
        const name = String(p?.name ?? "").trim();
        if (!name) continue;
        const cur = counts.get(name) || { id: p?.id ?? name, name, count: 0 };
        cur.count += 1;
        counts.set(name, cur);
      }
    }

    const all = Array.from(counts.values());

    const exact = all
      .filter((p) => p.count === wanted.length)
      .sort((a, b) => a.name.localeCompare(b.name, "pl"));

    const ranked = all
      .filter((p) => p.count < wanted.length)
      .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name, "pl"))
      .slice(0, 12);

    // ======= TEMATYCZNE (dodatki) =======
    const thematicMap = new Map(); // key = tid
    for (const ch of wanted) {
      const tp = Array.isArray(ch.thematic_packages)
        ? ch.thematic_packages
        : [];
      for (const p of tp) {
        const tid = String(p?.tid ?? "").trim();
        const name = String(p?.name ?? "").trim();
        if (!tid || !name) continue;
        if (!thematicMap.has(tid)) thematicMap.set(tid, { tid, name });
      }
    }

    const thematic = Array.from(thematicMap.values()).sort((a, b) =>
      a.name.localeCompare(b.name, "pl")
    );

    return { exact, ranked, thematic };
  }, [wanted]);

  return (
    <div class="f-chsearch">
      <h1 class="f-section-title">Wyszukiwanie kanałów w pakietach telewizji</h1>

      {/* ✅ SEKCJA "CHCIAŁBYM MIEĆ TE KANAŁY" */}
      <div class="f-chsearch__wanted">
        <div class="flex items-center justify-between gap-3 flex-wrap">
          <div class="text-lg font-semibold">Chciałbym mieć te kanały</div>

          {wanted.length > 0 && (
            <button type="button" class="btn btn-outline" onClick={clearWanted}>
              Wyczyść
            </button>
          )}
        </div>

        {wanted.length === 0 ? (
          <div class="opacity-80 mt-2">
            Dodaj kanały z listy wyników — pokażę pakiety, które zawierają
            wszystkie wybrane kanały.
          </div>
        ) : (
          <>
            <div class="f-chsearch__wanted-list">
              {wanted.map((w) => (
                <div class="f-chsearch__wanted-chip" key={w.name}>
                  {w.logo_url ? (
                    <img
                      src={w.logo_url}
                      alt={w.name}
                      class="f-chsearch__wanted-logo"
                      loading="lazy"
                    />
                  ) : null}
                  <span class="f-chsearch__wanted-name">{w.name}</span>
                  <button
                    type="button"
                    class="f-chsearch__wanted-remove"
                    aria-label={`Usuń ${w.name}`}
                    onClick={() => removeWantedByName(w.name)}
                  >
                    ✕
                  </button>
                </div>
              ))}
            </div>

            {/* ✅ SUGESTIE PAKIETÓW */}
            <div class="f-chsearch__wanted-packages">
              <div class="font-semibold">
                Pakiety pasujące do wybranych kanałów:
              </div>

              {/* ======= GŁÓWNE (jak było) ======= */}
              <div class="mt-2">
                <div class="opacity-80">Pakiety główne:</div>

                {packageSuggestions.exact.length > 0 ? (
                  <div class="flex flex-wrap gap-2 mt-2">
                    {packageSuggestions.exact.map((p) => (
                      <button
                        type="button"
                        key={p.name}
                        class="f-chsearch-pkg"
                        onClick={() => scrollToPackage(p.name)}
                        title="Kliknij, aby przewinąć do pakietu"
                      >
                        {p.name}
                      </button>
                    ))}
                  </div>
                ) : (
                  <div class="flex flex-wrap gap-2 mt-2">
                    {packageSuggestions.ranked.map((p) => (
                      <button
                        type="button"
                        key={p.name}
                        class="f-chsearch-pkg"
                        onClick={() => scrollToPackage(p.name)}
                        title={`Zawiera ${p.count}/${wanted.length} wybranych kanałów`}
                      >
                        {p.name} ({p.count}/{wanted.length})
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* ======= TEMATYCZNE — dodatki (bez liczenia) ======= */}
              {packageSuggestions.thematic.length > 0 && (
                <div class="mt-4">
                  <div class="opacity-80">
                    Pakiety tematyczne do dokupienia:
                  </div>

                  <div class="flex flex-wrap gap-2 mt-2">
                    {packageSuggestions.thematic.map((p) => (
                      <a
                        key={p.tid}
                        class="f-chsearch-pkg"
                        href={`/internet-telewizja/pakiety-tematyczne#${encodeURIComponent(
                          p.tid
                        )}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        title="Otwórz w nowej karcie"
                      >
                        {p.name}
                      </a>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </>
        )}
      </div>

      {/* SEARCH */}
      <div class="f-chsearch__top">
        <div class="f-chsearch__inputwrap">
          <input
            id="channel-search"
            class="f-chsearch__input"
            type="search"
            value={q}
            onInput={(e) => setQ(e.currentTarget.value)}
            placeholder="Szukaj kanału po nazwie…"
            aria-label="Szukaj kanału po nazwie"
          />

          {q && (
            <button
              type="button"
              class="f-chsearch__clear"
              aria-label="Wyczyść wyszukiwanie"
              onClick={() => setQ("")}
            >
              ✕
            </button>
          )}
        </div>

        <div class="f-chsearch-meta">{meta}</div>
      </div>

      {/* LIST */}
      <div class="f-chsearch__list" role="list">
        {items.map((c) => {
          const selected = isWanted(c);

          return (
            <div
              class="f-chsearch__row"
              role="listitem"
              key={`${c.name}-${c.logo_url || ""}`}
            >
              {/* kolumna 1 */}
              <div class="f-chsearch__left">
                {c.logo_url && (
                  <img
                    src={c.logo_url}
                    alt={c.name}
                    class="f-chsearch__logo"
                    loading="lazy"
                  />
                )}

                <div class="f-chsearch__channel-name">{c.name}</div>

                {/* ✅ przycisk dodaj/usuń */}
                <div class="mt-2">
                  {!selected ? (
                    <button
                      type="button"
                      class="btn btn-outline"
                      onClick={() => addWanted(c)}
                    >
                      Dodaj do “Chciałbym mieć”
                    </button>
                  ) : (
                    <button
                      type="button"
                      class="btn btn-primary"
                      onClick={() => removeWantedByName(c.name)}
                    >
                      Usuń z listy
                    </button>
                  )}
                </div>
              </div>

              {/* kolumna 2 */}
              <div class="f-chsearch__right">
                <div
                  class="f-chsearch__desc f-chsearch__desc--html"
                  dangerouslySetInnerHTML={{
                    __html: c.description || "<em>—</em>",
                  }}
                />

                {Array.isArray(c.packages) && c.packages.length > 0 && (
                  <div class="f-chsearch__packages">
                    Dostępny w pakietach:&nbsp;
                    {c.packages.map((p) => (
                      <span key={p.id}>
                        <button
                          type="button"
                          class="f-chsearch-pkg"
                          onClick={() => scrollToPackage(p.name)}
                          title="Kliknij, aby przewinąć do pakietu"
                        >
                          {p.name}
                        </button>
                      </span>
                    ))}
                  </div>
                )}

                {Array.isArray(c.thematic_packages) &&
                  c.thematic_packages.length > 0 && (
                    <div class="f-chsearch__packages">
                      Dostępny w pakietach tematycznych:&nbsp;
                      {c.thematic_packages.map((p) => (
                        <span key={`${p.tid}-${p.name}`}>
                          <a
                            class="f-chsearch-pkg"
                            href={`/internet-telewizja/pakiety-tematyczne#${encodeURIComponent(
                              p.tid
                            )}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            title="Otwórz w nowej karcie"
                          >
                            {p.name}
                          </a>
                        </span>
                      ))}
                    </div>
                  )}
              </div>
            </div>
          );
        })}

        {q.trim().length >= 1 && !loading && items.length === 0 && (
          <div class="f-chsearch-empty">
            Brak wyników dla: <strong>{q}</strong>
          </div>
        )}
      </div>
    </div>
  );
}
