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

interface WifiCredentials {
  ssid: string;
  password: string;
  security: string;
  hidden: boolean;
}

interface QRScannerProps {
  onScan: (credentials: WifiCredentials) => void;
  onClose: () => void;
  onError?: (error: string) => void;
}

/**
 * Parse WiFi QR code string
 * Format: WIFI:T:WPA;S:NetworkName;P:Password;H:true;;
 */
function parseWifiQR(text: string): WifiCredentials | null {
  if (!text.startsWith("WIFI:")) {
    return null;
  }

  const result: WifiCredentials = {
    ssid: "",
    password: "",
    security: "WPA",
    hidden: false,
  };

  // Remove WIFI: prefix and trailing ;;
  const data = text.slice(5).replace(/;;$/, "");

  // Parse key:value pairs separated by ;
  const parts = data.split(";");
  for (const part of parts) {
    const colonIdx = part.indexOf(":");
    if (colonIdx === -1) continue;

    const key = part.slice(0, colonIdx).toUpperCase();
    const value = part.slice(colonIdx + 1);

    switch (key) {
      case "S":
        result.ssid = value;
        break;
      case "P":
        result.password = value;
        break;
      case "T":
        result.security = value.toUpperCase();
        break;
      case "H":
        result.hidden = value.toLowerCase() === "true";
        break;
    }
  }

  // Unescape special characters
  result.ssid = result.ssid.replace(/\\;/g, ";").replace(/\\:/g, ":").replace(/\\\\/g, "\\");
  result.password = result.password.replace(/\\;/g, ";").replace(/\\:/g, ":").replace(/\\\\/g, "\\");

  return result.ssid ? result : null;
}

export default function QRScanner({ onScan, onClose, onError }: QRScannerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [scanning, setScanning] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [cameraReady, setCameraReady] = useState(false);
  const scannerRef = useRef<any>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const isRunningRef = useRef(false);

  // Safe stop function that checks scanner state
  const safeStopScanner = async () => {
    if (scannerRef.current && isRunningRef.current) {
      try {
        await scannerRef.current.stop();
        isRunningRef.current = false;
      } catch (err) {
        // Ignore stop errors - scanner may already be stopped
        console.debug("Scanner stop (already stopped):", err);
      }
    }
  };

  useEffect(() => {
    let mounted = true;
    let animationFrameId: number;

    const startScanner = async () => {
      try {
        // Import html5-qrcode dynamically (client-side only)
        const { Html5Qrcode } = await import("html5-qrcode");

        if (!mounted) return;

        const scanner = new Html5Qrcode("qr-reader");
        scannerRef.current = scanner;

        await scanner.start(
          { facingMode: "environment" },
          {
            fps: 10,
            qrbox: { width: 250, height: 250 },
          },
          (decodedText) => {
            const credentials = parseWifiQR(decodedText);
            if (credentials) {
              isRunningRef.current = false;
              scanner.stop().catch(console.error);
              onScan(credentials);
            } else {
              setError("Not a valid WiFi QR code");
              setTimeout(() => setError(null), 2000);
            }
          },
          () => {} // Ignore scan failures
        );

        if (mounted) {
          isRunningRef.current = true;
          setScanning(true);
          setCameraReady(true);
        }
      } catch (err: any) {
        console.error("QR Scanner error:", err);
        const errorMessage = err.message || "Failed to access camera";
        setError(errorMessage);
        onError?.(errorMessage);
      }
    };

    startScanner();

    return () => {
      mounted = false;
      safeStopScanner();
    };
  }, [onScan, onError]);

  const handleClose = () => {
    safeStopScanner();
    onClose();
  };

  return (
    <div
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: "rgba(var(--color-bg-rgb), 0.95)",
        backdropFilter: "blur(8px)",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 250,
        padding: "var(--space-4)",
      }}
    >
      <div
        style={{
          maxWidth: "400px",
          width: "100%",
          textAlign: "center",
        }}
      >
        <h3 style={{ marginBottom: "var(--space-4)", color: "var(--color-text)" }}>
          <span style={{ color: "var(--color-primary)" }}>📷</span> Scan WiFi QR Code
        </h3>

        <p style={{
          fontSize: "0.875rem",
          color: "var(--color-text-muted)",
          marginBottom: "var(--space-4)"
        }}>
          Point camera at a WiFi QR code to connect automatically
        </p>

        {/* QR Scanner Container */}
        <div
          id="qr-reader"
          style={{
            width: "100%",
            maxWidth: "350px",
            margin: "0 auto var(--space-4)",
            borderRadius: "var(--radius)",
            overflow: "hidden",
            background: "#000",
            minHeight: "300px",
          }}
        />

        {/* Status Messages */}
        {error && (
          <div
            style={{
              padding: "var(--space-3)",
              background: "rgba(var(--color-error-rgb), 0.1)",
              border: "1px solid var(--color-error)",
              borderRadius: "var(--radius)",
              marginBottom: "var(--space-4)",
              color: "var(--color-error)",
              fontSize: "0.875rem",
            }}
          >
            {error}
          </div>
        )}

        {!cameraReady && !error && (
          <div
            style={{
              padding: "var(--space-3)",
              marginBottom: "var(--space-4)",
              color: "var(--color-text-muted)",
              fontSize: "0.875rem",
            }}
          >
            <span className="spinner" style={{ marginRight: "var(--space-2)" }}></span>
            Initializing camera...
          </div>
        )}

        {/* Hint */}
        <div
          style={{
            fontSize: "0.75rem",
            color: "var(--color-text-muted)",
            marginBottom: "var(--space-4)",
            padding: "var(--space-3)",
            background: "var(--color-bg)",
            borderRadius: "var(--radius)",
          }}
        >
          <strong>Tip:</strong> Most routers have a WiFi QR code on a sticker.
          You can also generate one at{" "}
          <a
            href="https://qifi.org"
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: "var(--color-primary)" }}
          >
            qifi.org
          </a>
        </div>

        {/* Close Button */}
        <button
          type="button"
          className="btn btn-secondary"
          onClick={handleClose}
          style={{ width: "100%" }}
        >
          Cancel
        </button>
      </div>
    </div>
  );
}
