"use client";

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

interface Operator {
  id: string;
  name: string;
}

export default function OperatorLoginPage() {
  const router = useRouter();
  const [operators, setOperators] = useState<Operator[] | null>(null);
  const [selected, setSelected] = useState<Operator | null>(null);
  const [pin, setPin] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    fetch("/api/operators")
      .then((r) => r.json())
      .then((d) => setOperators(d.operators ?? []))
      .catch(() => setOperators([]));
  }, []);

  function pressKey(k: string) {
    setError(null);
    if (k === "back") {
      setPin((p) => p.slice(0, -1));
      return;
    }
    if (k === "clear") {
      setPin("");
      return;
    }
    setPin((p) => (p.length >= 4 ? p : p + k));
  }

  async function submit() {
    if (!selected || pin.length !== 4) return;
    setBusy(true);
    setError(null);
    try {
      const res = await fetch("/api/auth/operator/login", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ operatorId: selected.id, pin }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error ?? "Sign-in failed");
        setPin("");
        return;
      }
      router.push(data.redirect ?? "/op");
      router.refresh();
    } catch {
      setError("Network error");
    } finally {
      setBusy(false);
    }
  }

  useEffect(() => {
    if (pin.length === 4 && !busy) {
      void submit();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pin]);

  if (operators === null) {
    return (
      <main className="min-h-dvh flex items-center justify-center p-6 bg-slate-50">
        <p className="text-slate-500">Loading…</p>
      </main>
    );
  }

  if (!selected) {
    return (
      <main className="min-h-dvh p-6 bg-slate-50">
        <div className="mx-auto max-w-2xl">
          <div className="text-center mb-6">
            <h1 className="text-2xl font-semibold">Who are you?</h1>
            <p className="text-slate-500 mt-1">Tap your name to sign in.</p>
          </div>

          {operators.length === 0 ? (
            <div className="rounded-xl bg-white border border-slate-200 p-6 text-center">
              <p className="text-slate-700">No operators exist yet.</p>
              <p className="text-slate-500 text-sm mt-1">Ask an admin to create your account.</p>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {operators.map((op) => (
                <button
                  key={op.id}
                  onClick={() => setSelected(op)}
                  className="rounded-xl bg-white border border-slate-200 px-4 py-5 text-lg font-medium hover:border-slate-900 hover:shadow-sm transition"
                >
                  {op.name}
                </button>
              ))}
            </div>
          )}

          <div className="text-center mt-8">
            <Link href="/login" className="text-sm text-slate-500 hover:text-slate-900">
              ← Back
            </Link>
          </div>
        </div>
      </main>
    );
  }

  const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "clear", "0", "back"];

  return (
    <main className="min-h-dvh p-6 bg-slate-50">
      <div className="mx-auto max-w-sm">
        <div className="text-center mb-4">
          <button
            onClick={() => {
              setSelected(null);
              setPin("");
              setError(null);
            }}
            className="text-sm text-slate-500 hover:text-slate-900"
          >
            ← Not {selected.name}?
          </button>
        </div>

        <div className="rounded-2xl bg-white border border-slate-200 p-6 shadow-sm">
          <h1 className="text-xl font-semibold text-center">Hi, {selected.name}</h1>
          <p className="text-slate-500 text-sm text-center mt-1">Enter your 4-digit PIN</p>

          <div className="flex justify-center gap-3 my-6">
            {[0, 1, 2, 3].map((i) => (
              <div
                key={i}
                className={`w-4 h-4 rounded-full ${pin.length > i ? "bg-slate-900" : "bg-slate-200"}`}
              />
            ))}
          </div>

          {error && (
            <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-md px-3 py-2 mb-4 text-center">
              {error}
            </p>
          )}

          <div className="grid grid-cols-3 gap-2">
            {keys.map((k) => {
              const label = k === "back" ? "⌫" : k === "clear" ? "C" : k;
              return (
                <button
                  key={k}
                  onClick={() => pressKey(k)}
                  disabled={busy}
                  className="h-14 rounded-lg bg-slate-100 hover:bg-slate-200 active:bg-slate-300 text-xl font-medium transition disabled:opacity-60"
                >
                  {label}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </main>
  );
}
