"use client";

import { Suspense, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { CheckCircle2, XCircle, Loader2, ScanLine, LogIn } from "lucide-react";
import { scanTicketApi, type ScanResponse } from "@/api/client";
import { useAuthStore } from "@/store/authStore";

// ─── Types ────────────────────────────────────────────────────────────────────

type ScanStatus = "idle" | "loading" | "success" | "error";

// ─── Result screen ────────────────────────────────────────────────────────────

function ResultScreen({
  scanStatus,
  message,
  ticketId,
  onReset,
}: {
  scanStatus: "success" | "error";
  message: string;
  ticketId?: number;
  onReset: () => void;
}) {
  const isSuccess = scanStatus === "success";

  return (
    <div
      className={`flex flex-col items-center justify-center min-h-screen w-full px-6 transition-colors duration-300 ${
        isSuccess ? "bg-green-500" : "bg-red-500"
      }`}
    >
      {isSuccess ? (
        <CheckCircle2 className="text-white mb-6" size={120} strokeWidth={1.5} />
      ) : (
        <XCircle className="text-white mb-6" size={120} strokeWidth={1.5} />
      )}

      <p className="text-white text-[32px] font-black tracking-tight text-center uppercase leading-tight">
        {isSuccess ? "ПРОХОД РАЗРЕШЕН" : "ПРОХОД ЗАПРЕЩЕН"}
      </p>

      {ticketId && (
        <p className="text-white/70 text-[14px] font-medium mt-2">
          Билет #{ticketId}
        </p>
      )}

      <p className="text-white/90 text-[18px] font-semibold mt-4 text-center max-w-[300px] leading-snug">
        {message}
      </p>

      <button
        onClick={onReset}
        className="mt-12 px-8 py-3.5 bg-white/20 hover:bg-white/30 active:scale-95 transition-all rounded-2xl text-white text-[15px] font-semibold"
      >
        Сканировать следующий
      </button>
    </div>
  );
}

// ─── Loading screen ───────────────────────────────────────────────────────────

function LoadingScreen() {
  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-[#121212]">
      <Loader2 size={64} className="text-[#E32636] animate-spin mb-6" strokeWidth={1.5} />
      <p className="text-white text-[20px] font-bold">Проверка билета…</p>
      <p className="text-[#8E8E93] text-[13px] mt-2">Запрос к серверу</p>
    </div>
  );
}

// ─── Manual input form ────────────────────────────────────────────────────────

function ManualInput({
  onScan,
  loading,
}: {
  onScan: (token: string) => void;
  loading: boolean;
}) {
  const [value, setValue] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  // Auto-focus for USB barcode scanners (act as keyboard)
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const token = value.trim();
    if (token) onScan(token);
  }

  return (
    <form onSubmit={handleSubmit} className="w-full max-w-[340px] flex flex-col gap-3">
      <input
        ref={inputRef}
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Введите или отсканируйте токен…"
        autoComplete="off"
        autoCorrect="off"
        spellCheck={false}
        className="w-full bg-[#2C2C2E] border border-[#3A3A3C] focus:border-[#E32636] rounded-2xl px-5 py-4 text-[15px] text-white placeholder-[#4B5563] outline-none transition-colors text-center tracking-wide"
      />
      <button
        type="submit"
        disabled={loading || !value.trim()}
        className="w-full flex items-center justify-center gap-2 bg-[#E32636] hover:bg-[#C41E2A] disabled:opacity-50 disabled:cursor-not-allowed active:scale-95 transition-all text-white text-[16px] font-bold py-4 rounded-2xl"
      >
        {loading ? (
          <><Loader2 size={18} className="animate-spin" /> Проверка…</>
        ) : (
          <><ScanLine size={18} /> Проверить билет</>
        )}
      </button>
    </form>
  );
}

// ─── Core scanner logic (needs Suspense because of useSearchParams) ───────────

function ScannerCore() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = useAuthStore((s) => s.token);

  const [scanStatus, setScanStatus]   = useState<ScanStatus>("idle");
  const [message, setMessage]         = useState("");
  const [ticketId, setTicketId]       = useState<number | undefined>();
  const scanCalledRef                  = useRef(false);

  // Auth guard
  useEffect(() => {
    if (!token) router.push("/login");
  }, [token, router]);

  // Auto-scan when ?token= is present in the URL
  useEffect(() => {
    const urlToken = searchParams.get("token");
    if (!urlToken || scanCalledRef.current) return;
    scanCalledRef.current = true;
    void runScan(urlToken);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  async function runScan(rawToken: string) {
    setScanStatus("loading");
    setMessage("");
    setTicketId(undefined);

    const result: ScanResponse = await scanTicketApi(rawToken);

    setMessage(result.message);
    setTicketId(result.ticket_id);
    setScanStatus(result.success ? "success" : "error");
  }

  function handleReset() {
    setScanStatus("idle");
    setMessage("");
    setTicketId(undefined);
    scanCalledRef.current = false;
    // Clear the URL token so a fresh scan can be started
    router.replace("/scanner");
  }

  if (!token) return null;

  if (scanStatus === "loading") return <LoadingScreen />;

  if (scanStatus === "success" || scanStatus === "error") {
    return (
      <ResultScreen
        scanStatus={scanStatus}
        message={message}
        ticketId={ticketId}
        onReset={handleReset}
      />
    );
  }

  // ── Idle: manual input UI ──
  return (
    <div className="flex justify-center min-h-screen bg-[#121212]">
      <div className="w-full max-w-[390px] flex flex-col items-center px-5 pt-16 pb-10">

        {/* Brand / header */}
        <div className="w-16 h-16 rounded-2xl bg-[#E32636] flex items-center justify-center mb-6">
          <ScanLine size={32} className="text-white" strokeWidth={2} />
        </div>
        <h1 className="text-[26px] font-black text-white tracking-tight mb-1">
          Сканер билетов
        </h1>
        <p className="text-[13px] text-[#8E8E93] mb-10 text-center">
          Наведите QR-код или введите токен вручную
        </p>

        <ManualInput onScan={runScan} loading={false} />

        {/* Hint for USB scanners */}
        <p className="text-[11px] text-[#4B5563] mt-8 text-center leading-relaxed max-w-[260px]">
          USB-сканер работает как клавиатура —{"\n"}поле захватит фокус автоматически
        </p>

        <button
          onClick={() => router.push("/")}
          className="mt-auto pt-10 flex items-center gap-1.5 text-[12px] text-[#8E8E93] hover:text-white transition-colors"
        >
          <LogIn size={13} />
          На главную
        </button>
      </div>
    </div>
  );
}

// ─── Page export (wraps in Suspense for useSearchParams) ─────────────────────

export default function ScannerPage() {
  return (
    <Suspense
      fallback={
        <div className="flex items-center justify-center min-h-screen bg-[#121212]">
          <Loader2 size={40} className="text-[#E32636] animate-spin" />
        </div>
      }
    >
      <ScannerCore />
    </Suspense>
  );
}
