import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { AuthError, AuthLayout } from "@/components/pbps/auth-layout";
import { Button } from "@/components/ui/button";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { resendTwoFactor, verifyTwoFactor } from "@/api/auth";
import { landAfterLogin } from "@/lib/session-nav";

export const Route = createFileRoute("/verify")({
  validateSearch: (s: Record<string, unknown>) => ({
    c: String(s["c"] ?? ""),
    email: String(s["email"] ?? ""),
  }),
  head: () => ({ meta: [{ title: "Two-step verification — PBPS MIS" }] }),
  component: Verify,
});

function Verify() {
  const { c, email } = Route.useSearch();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [code, setCode] = useState("");
  const [wait, setWait] = useState(60);
  useEffect(() => {
    const t = setInterval(() => setWait((w) => Math.max(0, w - 1)), 1000);
    return () => clearInterval(t);
  }, []);
  const m = useMutation({
    mutationFn: () => verifyTwoFactor(c, code),
    onSuccess: () => landAfterLogin(navigate, qc),
  });
  const resend = useMutation({
    mutationFn: () => resendTwoFactor(c),
    onSuccess: () => {
      setWait(60);
      toast.success("A new code was sent.");
    },
  });
  if (!c)
    return (
      <AuthLayout title="Two-step verification">
        <p>
          This sign-in has expired.{" "}
          <Link to="/login" className="text-primary hover:underline">
            Sign in again
          </Link>
          .
        </p>
      </AuthLayout>
    );
  return (
    <AuthLayout
      title="Two-step verification"
      subtitle={<>Enter the 6-digit code we sent to {email || "your email"}.</>}
      footer={
        <Link to="/login" className="text-primary hover:underline">
          Back to sign in
        </Link>
      }
    >
      <form
        className="space-y-4"
        onSubmit={(e) => {
          e.preventDefault();
          if (code.length === 6) m.mutate();
        }}
      >
        <AuthError message={m.error?.message} />
        <InputOTP
          maxLength={6}
          value={code}
          onChange={(v) => {
            setCode(v);
            if (v.length === 6) setTimeout(() => m.mutate(), 0);
          }}
          autoFocus
        >
          <InputOTPGroup>
            {[0, 1, 2, 3, 4, 5].map((i) => (
              <InputOTPSlot key={i} index={i} />
            ))}
          </InputOTPGroup>
        </InputOTP>
        <Button
          type="submit"
          size="lg"
          className="w-full"
          disabled={code.length !== 6 || m.isPending}
        >
          {m.isPending ? "Verifying…" : "Verify"}
        </Button>
        <Button
          type="button"
          variant="ghost"
          className="w-full"
          disabled={wait > 0 || resend.isPending}
          onClick={() => resend.mutate()}
        >
          {wait > 0 ? `Resend code in ${wait} s` : "Resend code"}
        </Button>
      </form>
    </AuthLayout>
  );
}
