import { useEffect, useMemo, useState } from "preact/hooks";
import "../../styles/modal.css";
import "../../styles/offers/offers-table.css";
import "../../styles/channels-search.css"; // żeby input miał identyczny styl

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;
    if (!query.trim()) return `Wyniki: ${filtered.length} / ${channels.length}`;
    return `Wyniki: ${filtered.length} / ${channels.length}`;
  }, [loading, error, query, filtered.length, channels.length]);

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

    let cancelled = false;

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

      try {
        const params = new URLSearchParams({ packageId: String(pkg.id) });
        const res = await fetch(`/api/jambox/channels?${params.toString()}`);

        if (!res.ok) throw new Error(`HTTP ${res.status}`);

        const json = await res.json();
        if (!cancelled) setChannels(Array.isArray(json.data) ? json.data : []);
      } 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?.id]);

  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>

          {/* INPUT jak w wyszukiwarce (z własnym X) */}
          <div class="f-chsearch__top">
            <div class="f-chsearch__inputwrap">
              <input
                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()} // nie zabieraj focusa inputowi
                >
                  ✕
                </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="f-section-channel">
                  {filtered.map((ch) => (
                    <div
                      class="jmb-channel-card"
                      key={ch.number}
                      onClick={(e) => {
                        // żeby klik w link w opisie nie flipował
                        if (e.target.closest("a, button")) return;
                        e.currentTarget.classList.toggle("is-flipped");
                      }}
                    >
                      <div class="jmb-channel-inner">
                        {/* FRONT */}
                        <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 class="jmb-channel-number">kanał {ch.number}</div>
                        </div>

                        {/* BACK */}
                        <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>
  );
}
