import { useEffect, useState } from "preact/hooks";
import "../../styles/cards.css";

import OffersSwitches from "../Switches.jsx";
import JamboxChannelsModal from "./JamboxChannelsModal.jsx";
import JamboxAddonsModal from "./JamboxAddonsModal.jsx";
import Markdown from "../Markdown.jsx";

function formatMoney(amount, currency = "PLN") {
  if (typeof amount !== "number" || Number.isNaN(amount)) return "";
  try {
    return new Intl.NumberFormat("pl-PL", {
      style: "currency",
      currency,
      maximumFractionDigits: 0,
    }).format(amount);
  } catch {
    return String(amount);
  }
}

function toFeatureRows(params) {
  const list = Array.isArray(params) ? params : [];
  return list.map((p) => ({ label: p.label, value: p.value }));
}

/**
 * @typedef {{ label: string, value: any, klucz?: string }} Param
 * @typedef {{ id?: any, tid?: any, source?: string, nazwa?: string, slug?: string, ceny?: any[], parametry?: any[] }} Card
 * @typedef {{ id?: any, nazwa?: string }} PhoneCard
 * @typedef {{ id?: any, nazwa?: string }} Addon
 * @typedef {{ id?: any, nazwa?: string }} Decoder
 *
 * @typedef {{
 *  nazwa: string;
 *  opis?: string;
 *  image?: string;
 *  pakiety?: string[];
 * }} ChannelYaml
 *
 * @param {{
 *  title?: string,
 *  description?: string,
 *  cards?: Card[],
 *  internetWspolne?: Param[],
 *  waluta?: string,
 *  cenaOpis?: string,
 *
 *  phoneCards?: PhoneCard[],
 *  tvAddons?: any[],
 *  addons?: Addon[],
 *  decoders?: Decoder[],
 *  addonsCenaOpis?: string,
 *  channels?: ChannelYaml[],
 *  channels?: ChannelYaml[]
 * }} props
 */
export default function JamboxCards({
  title = "",
  description = "",
  cards = [],
  internetWspolne = [],
  waluta = "PLN",
  cenaOpis = "zł/mies.",

  phoneCards = [],
  tvAddons = [],
  addons = [],
  decoders = [],
  channels = [],
  switches = [],
}) {
  const visibleCards = Array.isArray(cards) ? cards : [];
  const wsp = Array.isArray(internetWspolne) ? internetWspolne : [];

  // stan switchera (window.fuzSwitchState + event)
  const [selected, setSelected] = useState({});
  const [labels, setLabels] = useState({});

  // modale
  const [channelsModalOpen, setChannelsModalOpen] = useState(false);
  const [addonsModalOpen, setAddonsModalOpen] = useState(false);
  const [activePkg, setActivePkg] = useState(null);

  useEffect(() => {
    if (typeof window !== "undefined" && window.fuzSwitchState) {
      const { selected: sel, labels: labs } = window.fuzSwitchState;
      if (sel) setSelected(sel);
      if (labs) setLabels(labs);
    }

    const handler = (e) => {
      const detail = e?.detail || {};
      if (detail.selected) setSelected(detail.selected);
      if (detail.labels) setLabels(detail.labels);
    };

    window.addEventListener("fuz:switch-change", handler);
    return () => window.removeEventListener("fuz:switch-change", handler);
  }, []);

  return (
    <section class="f-offers">
      {title && <h1 class="f-section-header">{title}</h1>}

      {description && (
        <div class="mb-4">
          <Markdown text={description} />
        </div>
      )}

      <OffersSwitches switches={switches} />

      {visibleCards.length === 0 ? (
        <p class="opacity-80">Brak pakietów do wyświetlenia.</p>
      ) : (
        <div class={`f-offers-grid f-count-${visibleCards.length || 1}`}>
          {visibleCards.map((card) => (
            <JamboxPackageCard
              key={card.id || card.nazwa}
              card={card}
              wsp={wsp}
              selected={selected}
              labels={labels}
              waluta={waluta}
              cenaOpis={cenaOpis}
              onShowChannels={(pkg) => {
                setActivePkg(pkg);
                setChannelsModalOpen(true);
              }}
              onConfigureAddons={(pkg) => {
                setActivePkg(pkg);
                setAddonsModalOpen(true);
              }}
            />
          ))}
        </div>
      )}

      <JamboxChannelsModal
        isOpen={channelsModalOpen}
        onClose={() => setChannelsModalOpen(false)}
        pkg={activePkg}
        allChannels={channels}
      />

      <JamboxAddonsModal
        isOpen={addonsModalOpen}
        onClose={() => setAddonsModalOpen(false)}
        pkg={activePkg}
        phoneCards={phoneCards}
        tvAddons={tvAddons}
        addons={addons}
        decoders={decoders}
        cenaOpis={cenaOpis}
      />
    </section>
  );
}

function JamboxPackageCard({
  card,
  wsp,
  selected,
  labels,
  waluta,
  cenaOpis,
  onShowChannels,
  onConfigureAddons,
}) {
  const baseParams = Array.isArray(card?.parametry) ? card.parametry : [];
  const ceny = Array.isArray(card?.ceny) ? card.ceny : [];

  const budynek = selected?.budynek;
  const umowa = selected?.umowa;

  const match = ceny.find(
    (c) => String(c?.budynek) === String(budynek) && String(c?.umowa) === String(umowa),
  );

  const basePrice = match?.miesiecznie;
  const installPrice = match?.aktywacja;

  const dynamicParams = [
    { klucz: "umowa", label: "Umowa", value: labels?.umowa || "—" },
    {
      klucz: "aktywacja",
      label: "Aktywacja",
      value: typeof installPrice === "number" ? formatMoney(installPrice, waluta) : "—",
    },
  ];

  const mergedParams = [...(Array.isArray(wsp) ? wsp : []), ...baseParams, ...dynamicParams];

  const pkgForModals = {
    id: card?.id,
    tid: card?.tid,
    source: card?.source,
    name: card?.nazwa,
    slug: card?.slug,
    price_monthly: typeof basePrice === "number" ? basePrice : null,
    price_installation: typeof installPrice === "number" ? installPrice : null,
    features: toFeatureRows(mergedParams),
  };

  const hasPrice = typeof basePrice === "number";

  return (
    <div class="f-card" id={`pkg-${card?.nazwa}`} data-pkg={card?.nazwa}  >
      <div class="f-card-header">
        <div class="f-card-name">{card.nazwa}</div>

        <div class="f-card-price">
          {hasPrice ? (
            <>
              {formatMoney(basePrice, waluta)} <span class="opacity-80">{cenaOpis}</span>
            </>
          ) : (
            <span class="opacity-70">Wybierz opcje</span>
          )}
        </div>
      </div>

      <ul class="f-card-features">
        {mergedParams.map((p, idx) => (
          <li class="f-card-row" key={p.klucz || p.label || idx}>
            <span class="f-card-label">{p.label}</span>
            <span class="f-card-value">{p.value}</span>
          </li>
        ))}
      </ul>

      <button
        type="button"
        class="btn btn-primary mt-2"
        disabled={!hasPrice}
        onClick={() => onShowChannels(pkgForModals)}
        title={!hasPrice ? "Wybierz typ budynku i umowę" : ""}
      >
        Pokaż listę kanałów
      </button>

      <button
        type="button"
        class="btn btn-primary mt-2"
        disabled={!hasPrice}
        onClick={() => onConfigureAddons(pkgForModals)}
        title={!hasPrice ? "Wybierz typ budynku i umowę" : ""}
      >
        Skonfiguruj usługi dodatkowe
      </button>
    </div>
  );
}
