"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

const MOBILE_USER_AGENT = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Silk|Kindle|Tablet|Mobile/i;

function isMobileAgent(userAgent: string, userAgentData?: { mobile?: boolean }) {
  return Boolean(
    userAgentData?.mobile || MOBILE_USER_AGENT.test(userAgent),
  );
}

export default function DesktopScanPrompt({
  runHref,
  partnerName = "",
  imei = "",
}: {
  runHref: string;
  partnerName?: string;
  imei?: string;
}) {
  const router = useRouter();
  const [isMobile, setIsMobile] = useState<boolean | null>(null);
  const [currentUrl, setCurrentUrl] = useState("");

  useEffect(() => {
    const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
    const userAgentData = typeof navigator !== "undefined" ? (navigator as any).userAgentData : undefined;

    setIsMobile(isMobileAgent(ua, userAgentData));
    setCurrentUrl(window.location.href);
  }, [imei, partnerName, router]);

  useEffect(() => {
    if (isMobile) {
      router.replace(runHref);
    }
  }, [isMobile, router, runHref]);

  if (isMobile === null) {
    return null;
  }

  if (isMobile) {
    return null;
  }

  const qrValue = encodeURIComponent(currentUrl || runHref);
  const qrSrc = `https://api.qrserver.com/v1/create-qr-code?size=320x320&data=${qrValue}`;

  return (
    <div className="min-h-screen bg-slate-50 py-16 px-4 sm:px-6 lg:px-8">
      <div className="mx-auto max-w-3xl rounded-[2rem] border border-slate-200 bg-white p-8 shadow-xl shadow-slate-200/50">
        <div className="text-center">
          <p className="text-sm font-semibold uppercase tracking-[0.3em] text-slate-500">
            Mobile test required
          </p>
          <h1 className="mt-4 text-3xl font-bold tracking-tight text-slate-900">
            Scan to begin the test on your phone
          </h1>
          <p className="mx-auto mt-4 max-w-2xl text-sm leading-6 text-slate-600">
            This test should be started from a mobile device. Scan the QR code below to continue immediately.
          </p>
        </div>

        <div className="mt-10 flex flex-col items-center gap-6">
          <div className="rounded-3xl border border-slate-200 bg-slate-100 p-4">
            <img
              src={qrSrc}
              alt="Scan this code with your mobile device to open the test"
              width={320}
              height={320}
              className="h-[320px] w-[320px]"
            />
          </div>
          <div className="text-center text-sm text-slate-500">
            If your mobile scanner cannot read the QR code, open this URL on your phone:
          </div>
          <div className="w-full overflow-x-auto rounded-3xl border border-slate-200 bg-slate-950 px-4 py-3 text-xs text-white">
            {currentUrl || runHref}
          </div>
        </div>
      </div>
    </div>
  );
}
