import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Loader2, Lock, ShieldCheck } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { supabase } from "@/integrations/supabase/client";
import { recordLoginEvent } from "@/lib/auth.functions";
import { getMe } from "@/lib/dashboard.functions";

export const Route = createFileRoute("/ebaybos/banger")({
  ssr: false,
  head: () => ({
    meta: [
      { title: "Administrator sign in" },
      { name: "robots", content: "noindex, nofollow" },
    ],
  }),
  beforeLoad: async () => {
    // If already signed in as admin, skip straight to admin dashboard.
    try {
      const { data } = await supabase.auth.getUser();
      if (data.user) {
        const { data: roles } = await supabase
          .from("user_roles")
          .select("role")
          .eq("user_id", data.user.id)
          .eq("role", "admin")
          .maybeSingle();
        if (roles) throw redirect({ to: "/ebaybos/admin/dashboard" });
      }
    } catch (e) {
      if ((e as { to?: string })?.to) throw e;
    }
  },
  component: BangerLogin,
});

function BangerLogin() {
  const navigate = useNavigate();
  const record = useServerFn(recordLoginEvent);
  const fetchMe = useServerFn(getMe);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const login = useMutation({
    mutationFn: async () => {
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;
      const me = await fetchMe({ data: undefined as never });
      if (!me.isAdmin) {
        await supabase.auth.signOut();
        throw new Error("This account is not an administrator.");
      }
      await record({ data: { event: "login" } }).catch(() => {});
    },
    onSuccess: () => {
      toast.success("Welcome, administrator");
      navigate({ to: "/ebaybos/admin/dashboard", replace: true });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-background via-background to-muted px-4">
      <div className="w-full max-w-sm rounded-2xl border bg-card p-8 shadow-lg">
        <div className="mb-6 flex flex-col items-center text-center">
          <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary">
            <ShieldCheck className="h-6 w-6" />
          </div>
          <h1 className="mt-4 text-xl font-semibold tracking-tight">Administrator sign in</h1>
          <p className="mt-1 text-xs text-muted-foreground">Restricted area. Authorized personnel only.</p>
        </div>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            login.mutate();
          }}
          className="space-y-4"
        >
          <div className="space-y-1.5">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              autoComplete="username"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <Button type="submit" className="w-full" disabled={login.isPending}>
            {login.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Lock className="mr-2 h-4 w-4" />
            )}
            Sign in
          </Button>
        </form>
      </div>
    </div>
  );
}
