"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import { billingApi, type BillingStatus } from "@/lib/api/billingApi";
import s from "./ClientBillingGate.module.css";

type Phase = "loading" | "paywall" | "confirming" | "success" | "done";

const LockIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="5" y="11" width="14" height="9" rx="2.2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" />
  </svg>
);
const MonitorIcon = () => (
  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="3" y="4" width="18" height="12" rx="1.6" /><path d="M8 20h8M12 16v4" />
  </svg>
);
const PhoneIcon = () => (
  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="7" y="2.5" width="10" height="19" rx="2.2" /><path d="M11 18.5h2" />
  </svg>
);
const Contactless = () => (
  <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true">
    <path d="M8.5 8a6 6 0 0 1 0 8M11.5 5.5a10 10 0 0 1 0 13M14.5 3a14 14 0 0 1 0 18" />
  </svg>
);
const StripeShield = () => (
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M12 2 4 5v6c0 5 3.5 8 8 11 4.5-3 8-6 8-11V5l-8-3Z" />
  </svg>
);
const Check = ({ size = 34 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M20 6 9 17l-5-5" />
  </svg>
);

const LINES = [16, 40, 64, 88, 112, 136, 160, 184, 208, 232];
const CardTexture = () => (
  <svg className={s.ccTexture} viewBox="0 0 380 240" preserveAspectRatio="none" aria-hidden="true">
    <g fill="none" stroke="#063a25" strokeOpacity="0.1" strokeWidth="1.1">
      {LINES.map((y, i) => (
        <path key={i} d={`M-10 ${y} C 70 ${y - 15}, 130 ${y + 15}, 200 ${y} S 320 ${y - 15}, 400 ${y}`} />
      ))}
    </g>
  </svg>
);

const Visa = () => (<span className={s.chipCard}><span className={s.visaTx}>VISA</span></span>);
const Mastercard = () => (
  <span className={s.chipCard}>
    <svg width="30" height="19" viewBox="0 0 34 22" aria-label="Mastercard">
      <circle cx="13" cy="11" r="7.4" fill="#EB001B" />
      <circle cx="21" cy="11" r="7.4" fill="#F79E1B" />
      <path d="M17 5.4a7.4 7.4 0 0 0 0 11.2 7.4 7.4 0 0 0 0-11.2Z" fill="#FF5F00" />
    </svg>
  </span>
);
const Amex = () => (<span className={s.chipCard}><span className={s.amexTx}>AMEX</span></span>);
const GooglePay = () => (
  <span className={s.chipCard}>
    <svg width="15" height="15" viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#4285F4" d="M45.12 24.5c0-1.56-.14-3.06-.4-4.5H24v8.51h11.84c-.51 2.75-2.06 5.08-4.39 6.64v5.52h7.11c4.16-3.83 6.56-9.47 6.56-16.17z" />
      <path fill="#34A853" d="M24 46c5.94 0 10.92-1.97 14.56-5.33l-7.11-5.52c-1.97 1.32-4.49 2.1-7.45 2.1-5.73 0-10.58-3.87-12.31-9.07H4.34v5.7C7.96 41.07 15.4 46 24 46z" />
      <path fill="#FBBC05" d="M11.69 28.18C11.25 26.86 11 25.45 11 24s.25-2.86.69-4.18v-5.7H4.34C2.85 17.09 2 20.45 2 24s.85 6.91 2.34 9.88l7.35-5.7z" />
      <path fill="#EA4335" d="M24 10.75c3.23 0 5.41 1.39 6.65 2.56l4.85-4.73C32.9 5.89 28.93 4 24 4 15.4 4 7.96 8.93 4.34 16.12l7.35 5.7c1.73-5.2 6.58-9.07 12.31-9.07z" />
    </svg>
    <span className={s.gpayTx}>Pay</span>
  </span>
);
const ApplePay = () => (
  <span className={s.chipCard}>
    <svg width="13" height="15" viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#000" d="M15.77 4.9c.78-.94 1.3-2.24 1.16-3.54-1.12.05-2.48.75-3.28 1.69-.72.83-1.35 2.16-1.18 3.43 1.25.1 2.52-.64 3.3-1.58zM17.5 12.5c-.03-2.9 2.37-4.29 2.48-4.36-1.35-1.98-3.46-2.25-4.21-2.28-1.79-.18-3.5 1.05-4.4 1.05-.91 0-2.31-1.03-3.8-1-1.95.03-3.75 1.13-4.75 2.88-2.03 3.52-.52 8.73 1.46 11.59.97 1.4 2.13 2.97 3.65 2.91 1.46-.06 2.01-.94 3.78-.94 1.76 0 2.26.94 3.8.91 1.57-.03 2.56-1.42 3.52-2.83 1.11-1.62 1.57-3.19 1.59-3.27-.03-.02-3.05-1.17-3.08-4.64z" />
    </svg>
    <span className={s.apayTx}>Pay</span>
  </span>
);

export default function ClientBillingGate({ children }: { children: React.ReactNode }) {
  const [phase, setPhase] = useState<Phase>("loading");
  const [status, setStatus] = useState<BillingStatus | null>(null);
  const [paying, setPaying] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [timedOut, setTimedOut] = useState(false);
  const started = useRef(false);
  const pollRef = useRef<number | null>(null);

  const fetchStatus = useCallback(async (): Promise<BillingStatus | null> => {
    try { const res = await billingApi.getStatus(); setStatus(res.data); return res.data; }
    catch { return null; }
  }, []);

  const cleanUrl = () => {
    const url = new URL(window.location.href);
    url.searchParams.delete("session_id");
    url.searchParams.delete("billing");
    window.history.replaceState({}, "", url.toString());
  };

  const celebrate = useCallback(() => {
    if (pollRef.current) window.clearInterval(pollRef.current);
    cleanUrl();
    setPhase("success");
    window.setTimeout(() => setPhase("done"), 1650);
  }, []);

  const startPolling = useCallback(() => {
    let tries = 0;
    pollRef.current = window.setInterval(async () => {
      tries += 1;
      const st = await fetchStatus();
      if (st && st.access_allowed !== false) celebrate();
      else if (tries >= 8) { if (pollRef.current) window.clearInterval(pollRef.current); setTimedOut(true); setPhase("paywall"); }
    }, 2500);
  }, [fetchStatus, celebrate]);

  useEffect(() => {
    if (started.current) return;
    started.current = true;
    (async () => {
      const st = await fetchStatus();
      const hasSession = !!new URLSearchParams(window.location.search).get("session_id");
      if (!st) { setPhase("done"); return; }
      if (st.access_allowed !== false) { setPhase("done"); return; }
      if (hasSession) { setPhase("confirming"); startPolling(); }
      else setPhase("paywall");
    })();
    return () => { if (pollRef.current) window.clearInterval(pollRef.current); };
  }, [fetchStatus, startPolling]);

  const payNow = async () => {
    setPaying(true); setErr(null);
    try {
      const res = await billingApi.createCheckoutSession();
      if (res?.data?.url) window.location.href = res.data.url;
      else { setErr("Could not start checkout. Please try again."); setPaying(false); }
    } catch (e: any) { setErr(e?.message || "Could not start checkout."); setPaying(false); }
  };

  const recheck = async () => {
    const st = await fetchStatus();
    if (st && st.access_allowed !== false) celebrate(); else setTimedOut(true);
  };

  if (phase === "done") return <div className={s.reveal}>{children}</div>;

  const amount = status?.price_amount ? (status.price_amount / 100).toFixed(2) : null;
  const currency = (status?.price_currency || "AED").toUpperCase();
  const interval = status?.price_interval || "year";
  const intervalLabel = interval === "month" ? "Monthly" : interval === "one_time" ? "One-time" : "Annual";

  return (
    <div className={s.page}>
      {phase === "confirming" && (
        <div className={`${s.card} ${s.center}`}>
          <div className={s.spinLg} />
          <h2 className={s.heading}>Confirming payment</h2>
          <p className={`${s.sub} ${s.subTight}`}>Securing your access — this only takes a moment.</p>
        </div>
      )}

      {phase === "success" && (
        <div className={`${s.card} ${s.center}`}>
          <div className={s.succ}><Check size={36} /></div>
          <h2 className={s.heading}>Payment successful</h2>
          <p className={`${s.sub} ${s.subTight}`}>Unlocking your portal…</p>
        </div>
      )}

      {phase === "paywall" && (
        <div className={s.card}>
          <p className={s.eyebrow}>Quality Registrar Systems</p>
          <h1 className={s.heading}>Portal Subscription</h1>
          <p className={s.sub}>
            Activate your subscription to unlock your certification portal — audits,
            certificates and reports — on web and mobile.
          </p>

          <div className={s.cc}>
            <CardTexture />
            <div className={s.ccTop}>
              <div className={s.ccChipRow}>
                <span className={s.chip} />
                <span className={s.contactless}><Contactless /></span>
              </div>
              <div className={s.ccBrand}>QRS<small>Portal Access</small></div>
            </div>

            {amount ? (
              <div className={s.ccPrice}>
                <span className={s.ccCur}>{currency}</span>
                <span className={s.ccAmt}>{amount}</span>
                <span className={s.ccInt}>/ {interval}</span>
              </div>
            ) : (
              <div className={s.ccPending}>Plan price pending</div>
            )}

            <div className={s.ccBottom}>
              <div className={s.ccField}>
                <label>Billed</label>
                <span>{intervalLabel}</span>
              </div>
              <span className={s.ccLogo} aria-hidden="true"><span /><span /></span>
            </div>
          </div>

          <div className={s.plats}>
            <span className={s.plat}><MonitorIcon /> Web portal</span>
            <span className={s.plat}><PhoneIcon /> Mobile app</span>
          </div>

          <button className={s.btn} onClick={payNow} disabled={paying || !amount}>
            {paying ? (<><span className={s.spin} /> Redirecting…</>) : (<><LockIcon size={16} /> Continue to secure payment</>)}
          </button>

          <div className={s.pay}><Visa /><Mastercard /><Amex /><GooglePay /><ApplePay /></div>
          <div className={s.stripe}><StripeShield /> Payments secured by Stripe</div>

          {!amount && (<div className={s.note}>Your plan price hasn’t been set yet. Please ask your administrator to set it, then reload.</div>)}
          {timedOut && (<div className={s.note}>Already paid? It can take a few seconds to confirm. <button className={s.link} onClick={recheck}>Check again</button></div>)}
          {err && <div className={s.err}>{err}</div>}
        </div>
      )}
    </div>
  );
}