"use client";

import { Apple, Check, Download, ExternalLink, QrCode, ShieldCheck, Smartphone, WifiOff } from "lucide-react";
import QRCode from "qrcode";
import { useEffect, useMemo, useState } from "react";
import { useTenant } from "@/components/tenant-provider";

type InstallPromptEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
};

export default function DownloadClient() {
  const { tenant } = useTenant();
  const [androidQr, setAndroidQr] = useState("");
  const [iosQr, setIosQr] = useState("");
  const [installPrompt, setInstallPrompt] = useState<InstallPromptEvent | null>(null);
  const [installed, setInstalled] = useState(false);

  const fallbackUrl = useMemo(() => {
    if (typeof window === "undefined") return `https://${tenant.customDomain || "e.zahratech.online"}/`;
    return `${window.location.origin}/?tenant=${encodeURIComponent(tenant.slug)}`;
  }, [tenant.customDomain, tenant.slug]);
  const androidUrl = tenant.androidAppUrl || fallbackUrl;
  const iosUrl = tenant.iosAppUrl || fallbackUrl;

  useEffect(() => {
    Promise.all([
      QRCode.toDataURL(androidUrl, { width: 360, margin: 2, color: { dark: tenant.secondaryColor, light: "#ffffff" }, errorCorrectionLevel: "H" }),
      QRCode.toDataURL(iosUrl, { width: 360, margin: 2, color: { dark: tenant.secondaryColor, light: "#ffffff" }, errorCorrectionLevel: "H" }),
    ]).then(([android, ios]) => { setAndroidQr(android); setIosQr(ios); }).catch(() => undefined);
  }, [androidUrl, iosUrl, tenant.secondaryColor]);

  useEffect(() => {
    const beforeInstall = (event: Event) => {
      event.preventDefault();
      setInstallPrompt(event as InstallPromptEvent);
    };
    const installedHandler = () => setInstalled(true);
    window.addEventListener("beforeinstallprompt", beforeInstall);
    window.addEventListener("appinstalled", installedHandler);
    return () => { window.removeEventListener("beforeinstallprompt", beforeInstall); window.removeEventListener("appinstalled", installedHandler); };
  }, []);

  async function installWebApp() {
    if (!installPrompt) return;
    await installPrompt.prompt();
    const result = await installPrompt.userChoice;
    if (result.outcome === "accepted") setInstalled(true);
    setInstallPrompt(null);
  }

  return (
    <main className="min-h-[calc(100vh-72px)] bg-[#f4f7fb]">
      <section className="relative overflow-hidden bg-[var(--navy)] px-5 py-16 text-white sm:py-20">
        <div className="absolute -right-28 -top-40 h-96 w-96 rounded-full bg-[var(--brand)] opacity-30 blur-3xl" />
        <div className="relative mx-auto max-w-5xl text-center">
          <span className="inline-flex items-center gap-2 rounded-full bg-white/10 px-3 py-1.5 text-[10px] font-black uppercase tracking-[0.15em] text-[var(--sun)]"><Smartphone size={14} /> {tenant.appName || `${tenant.brandName} App`}</span>
          <h1 className="mx-auto mt-5 max-w-3xl text-4xl font-black leading-tight tracking-[-0.045em] sm:text-6xl">Your favourite marketplace,<br /><span className="text-[var(--sun)]">now in your pocket.</span></h1>
          <p className="mx-auto mt-5 max-w-xl text-sm leading-7 text-blue-100">Scan the code for your phone or tap the download button. Shop products, receive alerts and track every order from {tenant.brandName}.</p>
        </div>
      </section>

      <section className="mx-auto max-w-5xl px-4 pb-16 sm:px-7">
        <div className="relative -mt-8 grid gap-5 md:grid-cols-2">
          <DownloadCard platform="Android" subtitle={tenant.androidAppUrl ? "Download APK / Open Play Store" : "Install secure web application"} url={androidUrl} qr={androidQr} icon={Smartphone} color="bg-green-600" configured={Boolean(tenant.androidAppUrl)} />
          <DownloadCard platform="iPhone" subtitle={tenant.iosAppUrl ? "Open in the Apple App Store" : "Add to your iPhone Home Screen"} url={iosUrl} qr={iosQr} icon={Apple} color="bg-slate-900" configured={Boolean(tenant.iosAppUrl)} />
        </div>

        <div className="mt-6 grid gap-5 lg:grid-cols-[1fr_0.65fr]">
          <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm sm:p-8">
            <div className="flex items-start gap-4"><span className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-blue-50 text-[var(--brand)]"><Download size={22} /></span><div><h2 className="text-xl font-black">Install directly from this browser</h2><p className="mt-2 text-sm leading-6 text-slate-500">The web application works like an app, opens full-screen, stays on your Home Screen and receives future updates automatically.</p></div></div>
            {installed ? <div className="mt-6 flex items-center gap-2 rounded-xl bg-green-50 p-4 text-xs font-black text-green-700"><Check size={16} /> {tenant.appName || tenant.brandName} is installed.</div> : installPrompt ? <button onClick={() => void installWebApp()} className="mt-6 flex w-full items-center justify-center gap-2 rounded-xl bg-[var(--brand)] px-5 py-3.5 text-sm font-black text-white"><Download size={17} /> Install {tenant.appName || `${tenant.brandName} App`}</button> : <div className="mt-6 rounded-xl bg-blue-50 p-4 text-xs leading-5 text-blue-800"><strong>Android:</strong> Open the browser menu and tap “Install app”.<br /><strong>iPhone:</strong> Open in Safari, tap Share, then “Add to Home Screen”.</div>}
          </section>
          <section className="rounded-3xl bg-[var(--navy)] p-6 text-white shadow-sm"><ShieldCheck size={24} className="text-[var(--sun)]" /><h2 className="mt-4 text-lg font-black">Safe installation</h2><div className="mt-4 space-y-3 text-[11px] leading-5 text-blue-100"><p className="flex gap-2"><Check size={14} className="mt-0.5 shrink-0 text-green-400" /> QR codes are generated securely inside this page.</p><p className="flex gap-2"><Check size={14} className="mt-0.5 shrink-0 text-green-400" /> Tenant download links are controlled from admin settings.</p><p className="flex gap-2"><WifiOff size={14} className="mt-0.5 shrink-0 text-green-400" /> Installed web app has an offline fallback.</p></div><p className="mt-6 border-t border-white/10 pt-4 text-[10px] text-blue-200">Help: {tenant.supportEmail}<br />{tenant.phonePrimary}</p></section>
        </div>
      </section>
    </main>
  );
}

function DownloadCard({ platform, subtitle, url, qr, icon: Icon, color, configured }: { platform: string; subtitle: string; url: string; qr: string; icon: React.ElementType; color: string; configured: boolean }) {
  return <article className="rounded-3xl border border-slate-200 bg-white p-6 shadow-[0_18px_45px_rgba(20,45,85,0.1)] sm:p-8"><div className="flex items-center justify-between"><span className={`grid h-12 w-12 place-items-center rounded-2xl text-white ${color}`}><Icon size={24} /></span><span className={`rounded-full px-2.5 py-1 text-[9px] font-black ${configured ? "bg-green-50 text-green-700" : "bg-orange-50 text-orange-700"}`}>{configured ? "STORE LINK READY" : "WEB APP FALLBACK"}</span></div><h2 className="mt-5 text-2xl font-black">Download for {platform}</h2><p className="mt-1 text-xs text-slate-500">{subtitle}</p><div className="mx-auto mt-6 grid aspect-square max-w-[235px] place-items-center overflow-hidden rounded-2xl border border-slate-200 bg-white p-3">{qr ? <img src={qr} alt={`${platform} application download QR code`} className="h-full w-full" /> : <QrCode size={80} className="animate-pulse text-slate-200" />}</div><p className="mt-3 text-center text-[9px] font-bold text-slate-400">SCAN WITH YOUR PHONE CAMERA</p><a href={url} target="_blank" rel="noreferrer" className={`mt-5 flex w-full items-center justify-center gap-2 rounded-xl px-5 py-3.5 text-xs font-black text-white ${color}`}><Download size={16} /> {configured ? `Get ${platform} app` : "Open installable app"} <ExternalLink size={13} /></a></article>;
}
