"use client";

import Image from "next/image";
import { useCallback, useEffect, useState } from "react";

type PermissionState = "granted" | "denied" | null;
type MotionPermissionState = "granted" | "denied" | "unsupported" | null;

type GrantedPermissions = {
  camera: PermissionState;
  mic: PermissionState;
  motion?: MotionPermissionState;
};

export type DiagnosticBrand = {
  brandName?: string;
  preflightTitle?: string;
  preflightCopy?: string;
  preflightNote?: string;
  poweredByLabel?: string;
  logoSrc?: string;
  logoAlt?: string;
  logoDark?: boolean;
};

interface PreFlightProps {
  mode: "quick" | "full";
  brand?: DiagnosticBrand;
  onBackHome?: () => void;
  onGranted: (permissions: GrantedPermissions) => void;
}

const icons = {
  target: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <circle cx="12" cy="12" r="10" />
      <path d="M22 12h-4M6 12H2M12 6V2M12 22v-4" />
    </svg>
  ),
  hand: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M18 11V6a2 2 0 0 0-4 0v5M14 10V4a2 2 0 0 0-4 0v11M10 10.5V6a2 2 0 0 0-4 0v8" />
      <path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15" />
    </svg>
  ),
  display: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <rect width="20" height="14" x="2" y="3" rx="2" />
      <path d="M8 21h8M12 17v4" />
    </svg>
  ),
};

export default function PreFlight({
  mode,
  brand = {},
  onBackHome,
  onGranted,
}: PreFlightProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSecureContextReady, setIsSecureContextReady] = useState(true);

  useEffect(() => {
    setIsSecureContextReady(window.isSecureContext);
  }, []);

  const mergedBrand = {
    brandName: mode === "quick" ? "Etisalat" : "Protect4Less",
    preflightTitle: "Device Diagnostics",
    preflightCopy:
      mode === "quick"
        ? "Run the focused touch and display verification flow."
        : "Run the complete diagnostic workflow and produce a certificate at the end.",
    preflightNote:
      "Your browser will ask for camera and microphone access. This data stays on your device and is never uploaded.",
    poweredByLabel: "Powered by",
    logoSrc: mode === "quick" ? "/eand-logo-white.svg" : "/p4l-logo.png",
    logoAlt: mode === "quick" ? "Etisalat" : "Protect4Less",
    logoDark: mode === "quick",
    ...brand,
  };

  const checks =
    mode === "quick"
      ? [
          { label: "Touch zones", desc: "Ensure touch detection across the display", icon: icons.target },
          { label: "Multi-touch", desc: "Detect simultaneous touch points and gestures", icon: icons.hand },
          { label: "Pixel drop", desc: "Scan for dead or stuck pixels in display colors", icon: icons.display },
        ]
      : [
          { label: "Camera Array", desc: "Front and rear camera detection" },
          { label: "Microphone", desc: "Audio input clarity test" },
          { label: "Sensors", desc: "Gyroscope, haptics and orientation" },
          { label: "Display", desc: "Touch zones and panel uniformity" },
        ];

  const requestPermissions = useCallback(async () => {
    setLoading(true);
    setError(null);

    if (!window.isSecureContext) {
      setError(
        "Camera, microphone, and motion permissions require HTTPS or localhost.",
      );
      setLoading(false);
      return;
    }

    if (!navigator.mediaDevices?.getUserMedia) {
      setError(
        "This browser cannot request camera and microphone access from the current page.",
      );
      setLoading(false);
      return;
    }

    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true,
      });
      stream.getTracks().forEach((track) => track.stop());
      onGranted({ camera: "granted", mic: "granted", motion: null });
    } catch {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        stream.getTracks().forEach((track) => track.stop());
        onGranted({ camera: "granted", mic: "denied", motion: null });
      } catch {
        setError(
          "Camera access is required to run the diagnostic. Please allow access and try again.",
        );
        setLoading(false);
      }
    }
  }, [onGranted]);

  return (
    <div className="relative min-h-screen overflow-hidden bg-white">
      <div className="pointer-events-none fixed inset-0 overflow-hidden">
        <div className="absolute -left-32 -top-32 h-[600px] w-[600px] rounded-full bg-p4l-red opacity-20 blur-[160px]" />
        <div className="absolute -bottom-40 -right-24 h-[500px] w-[500px] rounded-full bg-slate-900 opacity-10 blur-[180px]" />
      </div>

      <main className="relative mx-auto flex min-h-screen max-w-[1200px] items-center px-4 py-6 sm:px-8 lg:px-12 lg:py-10">
        <div className="grid w-full items-center gap-6 lg:grid-cols-[1.15fr_0.85fr] lg:gap-8">
          <div className="space-y-6 lg:space-y-8">
            <div className="flex flex-col items-center gap-4 text-center">
              <button
                type="button"
                onClick={onBackHome}
                aria-label="Back to home"
                className={`flex h-20 w-20 shrink-0 items-center justify-center rounded-3xl sm:h-24 sm:w-24 ${
                  mergedBrand.logoDark
                    ? "bg-slate-900"
                    : "border border-slate-200 bg-white shadow-[0_18px_45px_rgba(15,23,42,0.08)]"
                }`}
              >
                <Image
                  src={mergedBrand.logoSrc}
                  alt={mergedBrand.logoAlt}
                  width={56}
                  height={56}
                  className="h-12 w-12 object-contain sm:h-14 sm:w-14"
                />
              </button>
              <div>
                <h1 className="text-3xl font-black leading-tight tracking-tight text-slate-950 sm:text-4xl lg:text-5xl">
                  {mergedBrand.preflightTitle}
                </h1>
                <p className="mx-auto mt-3 max-w-xl text-sm leading-relaxed text-slate-500">
                  {mergedBrand.preflightCopy}
                </p>
              </div>
            </div>

            <section className="rounded-[1.75rem] border border-white/80 bg-white/70 p-5 shadow-[0_4px_24px_rgba(15,23,42,0.07)] backdrop-blur-xl sm:p-6">
              <p className="mb-4 text-[10px] font-bold uppercase tracking-[0.28em] text-slate-400">
                What we&apos;ll check
              </p>
              <div className="grid gap-3 sm:grid-cols-2">
                {checks.map((item) => (
                  <div
                    key={item.label}
                    className="flex items-start gap-3 rounded-2xl border border-white/70 bg-white/50 px-4 py-4 backdrop-blur-sm"
                  >
                    {"icon" in item ? (
                      <span className="mt-0.5 shrink-0 text-slate-500">
                        {item.icon}
                      </span>
                    ) : (
                      <span className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full bg-p4l-red" />
                    )}
                    <div>
                      <p className="text-sm font-semibold text-slate-950">
                        {item.label}
                      </p>
                      <p className="mt-0.5 text-[11px] leading-tight text-slate-500">
                        {item.desc}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          </div>

          <div className="w-full max-w-xl lg:justify-self-end">
            <section className="space-y-4 rounded-[2rem] border border-white/80 bg-white/70 p-5 shadow-[0_4px_24px_rgba(15,23,42,0.07)] backdrop-blur-xl sm:p-6">
              {!isSecureContextReady && (
                <div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-left text-sm text-amber-900">
                  This session is not secure. Open the app over HTTPS or
                  localhost to grant device permissions.
                </div>
              )}

              {error && (
                <div className="rounded-xl border border-red-200 bg-red-50 p-3 text-left text-sm text-red-700">
                  {error}
                </div>
              )}

              <button
                onClick={requestPermissions}
                disabled={loading}
                className="btn-primary disabled:opacity-60"
                id="begin-scan-btn"
              >
                {loading ? "Requesting Access..." : "Begin Diagnostics"}
              </button>

              <div className="flex items-start gap-2 text-left">
                <svg className="mt-0.5 h-3.5 w-3.5 shrink-0 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 100 20 10 10 0 000-20z" />
                </svg>
                <p className="text-xs leading-relaxed text-slate-400">
                  {mergedBrand.preflightNote}
                </p>
              </div>
            </section>

            <div className="mt-8 text-center lg:text-right">
              <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
                {mergedBrand.poweredByLabel}
              </p>
              <Image
                src="/p4l-logo.png"
                alt="Protect4Less"
                width={72}
                height={20}
                className="mx-auto mt-1 h-5 w-auto object-contain lg:ml-auto lg:mr-0"
              />
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
