"use client";

import { useEffect, useMemo, useState } from "react";

type Config = {
  settings: { price: number; redirectUrl: string; popupTitle: string; popupDescription: string };
  media: { id: string; filename: string; url: string }[];
};

const fallback: Config = {
  settings: {
    price: 2000,
    redirectUrl: "#",
    popupTitle: "Lipia ili kuendelea",
    popupDescription: "Weka namba yako ya simu yenye pesa. Utapokea ombi la kuthibitisha malipo.",
  },
  media: [],
};

export function CustomerExperience() {
  const [config, setConfig] = useState<Config>(fallback);
  const [active, setActive] = useState(0);
  const [modalOpen, setModalOpen] = useState(false);
  const [phone, setPhone] = useState("");
  const [busy, setBusy] = useState(false);
  const [notice, setNotice] = useState("");

  useEffect(() => {
    fetch("/api/public-config", { cache: "no-store" })
      .then((response) => response.ok ? response.json() : Promise.reject())
      .then(setConfig)
      .catch(() => setNotice("Mipangilio haikupatikana. Jaribu tena baadaye."));
    const timer = window.setTimeout(() => setModalOpen(true), 10000);
    return () => window.clearTimeout(timer);
  }, []);

  const current = config.media[active];
  const formattedPrice = useMemo(
    () => new Intl.NumberFormat("sw-TZ", { maximumFractionDigits: 0 }).format(config.settings.price),
    [config.settings.price],
  );

  async function pay(event: React.FormEvent) {
    event.preventDefault();
    setBusy(true);
    setNotice("Tunatuma ombi la malipo kwenye simu yako…");
    try {
      const createResponse = await fetch("/api/payment/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone }),
      });
      const created = await createResponse.json();
      if (!createResponse.ok) throw new Error(created.message || "Malipo hayakuanzishwa.");
      setNotice("Thibitisha malipo kwenye simu yako. Tunakagua hali…");
      for (let attempt = 0; attempt < 9; attempt += 1) {
        await new Promise((resolve) => window.setTimeout(resolve, attempt === 0 ? 1200 : 3000));
        const statusResponse = await fetch("/api/payment/status", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ orderId: created.orderId }),
        });
        const status = await statusResponse.json();
        if (statusResponse.ok && ["SUCCESS", "COMPLETED"].includes(status.paymentStatus)) {
          setNotice("Malipo yamekamilika. Tunakuelekeza sasa…");
          window.location.assign(config.settings.redirectUrl);
          return;
        }
      }
      throw new Error("Malipo bado hayajakamilika. Thibitisha ombi kisha ujaribu tena.");
    } catch (error) {
      setNotice(error instanceof Error ? error.message : "Hitilafu imetokea. Jaribu tena.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className="customer-shell">
      <header className="customer-header">
        <a className="brand" href="#top" aria-label="Project Loyd home">
          <span className="brand-mark">L</span>
          <span>PROJECT LOYD</span>
        </a>
        <button className="header-action" onClick={() => setModalOpen(true)}>Fungua sasa</button>
      </header>

      <section className="hero" id="top">
        <div className="hero-copy">
          <span className="eyebrow"><i /> MAUDHUI MAPYA</span>
          <h1>Tazama. Lipia.<br /><em>Fungua papo hapo.</em></h1>
          <p>Njia rahisi na salama ya kufungua video kupitia malipo ya simu.</p>
          <div className="hero-actions">
            <button className="primary-button" onClick={() => setModalOpen(true)}>Fungua video <span>→</span></button>
            <span className="price-note">TSH {formattedPrice}<small>malipo mara moja</small></span>
          </div>
        </div>

        <div className="media-stage">
          <span className="age-badge">18+</span>
          {current ? (
            <img src={current.url} alt={current.filename || "Project Loyd media"} />
          ) : (
            <div className="media-placeholder">
              <span className="play-symbol">▶</span>
              <p>Media mpya inaandaliwa</p>
            </div>
          )}
          <button className="stage-cta" onClick={() => setModalOpen(true)}><span>▶</span> Fungua kutazama</button>
        </div>
      </section>

      {config.media.length > 1 && (
        <section className="gallery-strip" aria-label="Media gallery">
          {config.media.map((item, index) => (
            <button key={item.id} className={index === active ? "thumb active" : "thumb"} onClick={() => setActive(index)}>
              <img src={item.url} alt={item.filename} /><span>{String(index + 1).padStart(2, "0")}</span>
            </button>
          ))}
        </section>
      )}

      <section className="trust-row">
        <div><strong>01</strong><span>Malipo ya simu</span></div>
        <div><strong>02</strong><span>Ufunguzi wa haraka</span></div>
        <div><strong>03</strong><span>Muamala salama</span></div>
      </section>

      <footer><span>© {new Date().getFullYear()} Project Loyd</span><a href="/admin">Admin</a></footer>

      {modalOpen && (
        <div className="modal-backdrop" role="presentation">
          <section className="payment-modal" role="dialog" aria-modal="true" aria-labelledby="payment-title">
            <button className="modal-close" onClick={() => !busy && setModalOpen(false)} aria-label="Close">×</button>
            <span className="modal-kicker">SECURE CHECKOUT</span>
            <h2 id="payment-title">{config.settings.popupTitle}</h2>
            <p>{config.settings.popupDescription}</p>
            <div className="amount-line"><span>Kiasi</span><strong>TSH {formattedPrice}</strong></div>
            <form onSubmit={pay}>
              <label htmlFor="phone">Namba ya simu yenye pesa</label>
              <div className="phone-field"><span>+255</span><input id="phone" value={phone} onChange={(event) => setPhone(event.target.value)} placeholder="712 345 678" inputMode="tel" autoComplete="tel" required /></div>
              <button className="pay-button" disabled={busy}>{busy ? "Subiri…" : `LIPIA TSH ${formattedPrice}`} <span>→</span></button>
            </form>
            {notice && <p className="payment-notice" aria-live="polite">{notice}</p>}
            <small className="secure-note">🔒 Taarifa zako zinalindwa wakati wa malipo.</small>
          </section>
        </div>
      )}
    </main>
  );
}
