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

export default function JamboxChannelsModal({ isOpen, onClose, pkg }) {
  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [query, setQuery] = useState("");

  const q = query.trim().toLowerCase();

  const filtered = !q
    ? channels
    : channels.filter((ch) => (ch.name || "").toLowerCase().includes(q));

  const meta = useMemo(() => {
    if (loading) return "Ładowanie…";
    if (error) return error;
    return `Wyniki: ${filtered.length} / ${channels.length}`;
  }, [loading, error, filtered.length, channels.length]);

  useEffect(() => {
    if (!isOpen || !pkg?.name) return;

    let cancelled = false;

    async function loadChannels() {
      setLoading(true);
      setError("");
      setChannels([]);
      setQuery("");

      try {
        // ✅ NOWE API: po nazwie pakietu
        const params = new URLSearchParams({ package: String(pkg.name) });
        const res = await fetch(`/api/jambox/jambox-channels-package?${params.toString()}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);

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

        const list = Array.isArray(json.data) ? json.data : [];

        // ✅ Normalizacja do UI (żeby reszta modala się nie sypała)
        // - number: nie ma w DB, więc dajemy null/"—"
        const normalized = list.map((ch, i) => ({
          name: ch?.name ?? "",
          description: ch?.description ?? "",
          logo_url: ch?.logo_url ?? "",
          number: ch?.number ?? "—",
          _key: `${ch?.name ?? "?"}-${i}`,
        }));

        if (!cancelled) setChannels(normalized);
      } catch (err) {
        console.error("❌ Błąd pobierania listy kanałów:", err);
        if (!cancelled) setError("Nie udało się załadować listy kanałów.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    loadChannels();
    return () => {
      cancelled = true;
    };
  }, [isOpen, pkg?.name]);

  if (!isOpen || !pkg) return null;

  return (
    <div class="f-modal-overlay" onClick={onClose}>
      <button
        class="f-modal-close"
        onClick={(e) => {
          e.stopPropagation();
          onClose();
        }}
        aria-label="Zamknij"
        type="button"
      >
        ✕
      </button>

      <div
        class="f-modal-panel f-modal-panel--channels"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={`Kanały w pakiecie ${pkg.name}`}
      >
        <div class="max-w-8xl mx-auto px-3 md:px-6">
          <h2 class="f-modal-title">Kanały w pakiecie {pkg.name}</h2>

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

              {query && (
                <button
                  type="button"
                  class="f-chsearch__clear"
                  aria-label="Wyczyść wyszukiwanie"
                  onClick={() => setQuery("")}
                  onMouseDown={(e) => e.preventDefault()}
                >
                  ✕
                </button>
              )}
            </div>

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

          {loading && <p>Ładowanie kanałów...</p>}
          {error && !loading && <p class="text-red-600">{error}</p>}

          {!loading && !error && (
            <>
              {filtered.length === 0 ? (
                <p>Brak kanałów spełniających kryteria.</p>
              ) : (
                <div class="jmb-channels-grid">
                  {filtered.map((ch) => (
                    <div
                      class="jmb-channel-card"
                      key={ch._key}
                      role="button"
                      tabIndex={0}
                      onClick={(e) => {
                        if (e.target.closest("a, button")) return;
                        e.currentTarget.classList.toggle("is-flipped");
                      }}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") {
                          e.preventDefault();
                          e.currentTarget.classList.toggle("is-flipped");
                        }
                      }}
                    >
                      <div class="jmb-channel-inner">
                        <div class="jmb-channel-face jmb-channel-front">
                          {ch.logo_url && (
                            <img
                              src={ch.logo_url}
                              alt={ch.name}
                              class="jmb-channel-logo"
                              loading="lazy"
                            />
                          )}
                          <div class="jmb-channel-name">{ch.name}</div>


                        </div>

                        <div class="jmb-channel-face jmb-channel-back">
                          <div class="jmb-channel-back-title">{ch.name}</div>
                          <div
                            class="jmb-channel-desc"
                            dangerouslySetInnerHTML={{
                              __html: ch.description || "<em>Brak opisu kanału.</em>",
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
