import { useState } from "react";
import { motion } from "framer-motion";
import { ArrowLeft, Tv, Cpu, KeyRound, Loader2, ShieldCheck } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";

const API =
  import.meta.env.VITE_BACKEND_URL ||
  import.meta.env.REACT_APP_BACKEND_URL ||
  "";

/**
 * Device Login — MAC address + 6-digit PIN authentication.
 *
 * The TV / device app registers itself via /api/device/register and
 * obtains its MAC + PIN. This screen is the inverse: a portal where
 * the user can authenticate ANY device against the backend by typing
 * those two values, then land on the member hub (Subscribe / Pair /
 * Privacy). Used as a lightweight licence-gate for the activation
 * portal (so random visitors can't reach the signup form directly).
 */
const DeviceLogin = () => {
  const navigate = useNavigate();
  const [mac, setMac] = useState("");
  const [pin, setPin] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  // Auto-format MAC: "AABBCCDDEEFF" → "AA:BB:CC:DD:EE:FF"
  const formatMac = (raw: string): string => {
    const hex = raw.replace(/[^0-9a-fA-F]/g, "").slice(0, 12).toUpperCase();
    return hex.match(/.{1,2}/g)?.join(":") ?? hex;
  };

  const handleMacChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setMac(formatMac(e.target.value));
  };

  const handlePinChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const v = e.target.value.replace(/\D/g, "").slice(0, 6);
    setPin(v);
  };

  const submit = async () => {
    setError("");
    const cleanMac = mac.trim().toUpperCase();
    if (cleanMac.replace(/[^0-9A-F]/g, "").length !== 12) {
      setError("Enter a valid MAC address (12 hex characters)");
      return;
    }
    if (pin.length !== 6) {
      setError("Enter the 6-digit PIN");
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`${API}/api/device/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mac_address: cleanMac, pin }),
      });
      if (!res.ok) {
        const j = await res.json().catch(() => ({}));
        throw new Error(j.detail || "Login failed");
      }
      const data = await res.json();
      // Persist the session so the hub page knows we're authenticated.
      localStorage.setItem(
        "nadi_device_session",
        JSON.stringify({ ...data, ts: Date.now() }),
      );
      toast.success("Device authenticated");
      navigate("/member-hub");
    } catch (e: any) {
      setError(e?.message || "Invalid MAC or PIN");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="relative h-screen w-full overflow-hidden flex items-center justify-center px-4 py-6 sm:py-10"
      data-testid="device-login-page"
    >
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat opacity-40"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="absolute inset-0 bg-background/60" />

      <button
        onClick={() => navigate("/welcome")}
        className="absolute z-20 top-4 sm:top-6 start-4 sm:start-6 w-10 h-10 rounded-full glass flex items-center justify-center text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors"
        data-testid="device-login-back"
        aria-label="Back"
      >
        <ArrowLeft className="w-4 h-4 rtl:rotate-180" />
      </button>

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative z-10 glass-card rounded-2xl sm:rounded-3xl p-5 sm:p-8 w-full max-w-[360px] sm:max-w-md"
      >
        <div className="flex flex-col items-center mb-5">
          <div className="w-12 h-12 sm:w-14 sm:h-14 rounded-2xl glass flex items-center justify-center mb-3">
            <Tv className="w-5 h-5 sm:w-6 sm:h-6 text-primary" />
          </div>
          <h1 className="font-display text-xl sm:text-2xl tracking-[0.25em] gold-text">
            DEVICE LOGIN
          </h1>
          <p className="text-muted-foreground text-[10px] sm:text-xs mt-1 tracking-[0.2em] uppercase">
            MAC + PIN authentication
          </p>
        </div>

        <div className="space-y-3">
          {/* MAC field */}
          <label className="block">
            <span className="text-[10px] tracking-[0.25em] uppercase text-muted-foreground">
              MAC Address
            </span>
            <div className="flex items-center gap-3 glass-input rounded-xl px-4 py-3 mt-1">
              <Cpu className="w-4 h-4 text-primary shrink-0" />
              <input
                type="text"
                value={mac}
                onChange={handleMacChange}
                placeholder="AA:BB:CC:DD:EE:FF"
                inputMode="text"
                autoCapitalize="characters"
                spellCheck={false}
                data-testid="device-login-mac-input"
                className="flex-1 bg-transparent text-foreground text-sm outline-none placeholder:text-muted-foreground tabular-nums tracking-wider"
              />
            </div>
          </label>

          {/* PIN field */}
          <label className="block">
            <span className="text-[10px] tracking-[0.25em] uppercase text-muted-foreground">
              6-Digit PIN
            </span>
            <div className="flex items-center gap-3 glass-input rounded-xl px-4 py-3 mt-1">
              <KeyRound className="w-4 h-4 text-primary shrink-0" />
              <input
                type="text"
                value={pin}
                onChange={handlePinChange}
                placeholder="••••••"
                inputMode="numeric"
                maxLength={6}
                data-testid="device-login-pin-input"
                className="flex-1 bg-transparent text-foreground text-base outline-none placeholder:text-muted-foreground tabular-nums tracking-[0.4em] font-medium"
              />
            </div>
          </label>

          {error && (
            <div
              className="text-destructive text-xs px-3 py-2 rounded-lg border border-destructive/40 bg-destructive/10"
              data-testid="device-login-error"
            >
              {error}
            </div>
          )}

          <button
            type="button"
            onClick={() => { if (!loading) submit(); }}
            aria-busy={loading || undefined}
            data-loading={loading || undefined}
            data-testid="device-login-submit"
            className={`w-full mt-2 py-3 rounded-xl bg-gradient-to-r from-primary to-primary/80 text-primary-foreground font-medium text-sm tracking-[0.2em] uppercase hover:from-primary hover:to-primary transition-all flex items-center justify-center gap-2 ${loading ? "opacity-60 pointer-events-none cursor-wait" : ""}`}
          >
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" /> Authenticating...
              </>
            ) : (
              <>
                <ShieldCheck className="w-4 h-4" /> Login
              </>
            )}
          </button>

          <p className="text-muted-foreground text-[10px] sm:text-[11px] text-center mt-2 leading-relaxed">
            Find your MAC + PIN on the device activation screen
            <br />
            (TV / mobile app → Settings → Activate device).
          </p>
        </div>
      </motion.div>
    </div>
  );
};

export default DeviceLogin;
