import { useCallback, useEffect, useState, type FormEvent } from "react";
import { Route, Switch, useRoute } from "wouter";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiRequest } from "@/lib/queryClient";
import AdminLayout from "./AdminLayout";
import AdminOverview from "./AdminOverview";
import AdminUsers from "./AdminUsers";
import AdminUserDetail from "./AdminUserDetail";
import AdminRuns from "./AdminRuns";
import AdminRunDetail from "./AdminRunDetail";
import AdminInvariants from "./AdminInvariants";
import AdminSupportTickets from "./AdminSupportTickets";
import NotFound from "@/pages/not-found";
import {
  fetchAdminJson,
  getAdminAccessState,
  getAdminErrorMessage,
} from "./api";
import type { AdminAccessResponse } from "./types";

type AccessState = "loading" | "allowed" | "unauthenticated" | "forbidden" | "unavailable";

type LoginForm = {
  email: string;
  password: string;
};

export default function AdminPage() {
  const [accessState, setAccessState] = useState<AccessState>("loading");
  const [accessError, setAccessError] = useState<string | null>(null);
  const [adminUser, setAdminUser] = useState<AdminAccessResponse | null>(null);
  const [loginForm, setLoginForm] = useState<LoginForm>({ email: "", password: "" });
  const [loginError, setLoginError] = useState<string | null>(null);
  const [loginPending, setLoginPending] = useState(false);
  const [, userParams] = useRoute("/admin/users/:userId");
  const [, runParams] = useRoute("/admin/runs/:runId");

  const checkAccess = useCallback(async () => {
    setAccessState("loading");
    setAccessError(null);
    try {
      const access = await fetchAdminJson<AdminAccessResponse>("admin/access");
      if (!access) {
        setAdminUser(null);
        setAccessState("forbidden");
        return;
      }
      setAdminUser(access);
      setAccessState("allowed");
    } catch (error) {
      setAdminUser(null);
      setAccessError(getAdminErrorMessage(error, "Cannot load admin access."));
      setAccessState(getAdminAccessState(error));
    }
  }, []);

  useEffect(() => {
    checkAccess();
  }, [checkAccess]);

  const handleLogin = async (event: FormEvent) => {
    event.preventDefault();
    if (!loginForm.email.trim() || !loginForm.password) {
      setLoginError("Email and password are required.");
      return;
    }

    setLoginPending(true);
    setLoginError(null);
    try {
      await apiRequest("POST", "login", {
        email: loginForm.email.trim(),
        password: loginForm.password,
      });
      await checkAccess();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Login failed";
      setLoginError(message);
      setAccessState("unauthenticated");
    } finally {
      setLoginPending(false);
    }
  };

  if (accessState === "loading") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#05070d] px-4 text-sm text-muted-foreground">
        Checking admin access...
      </div>
    );
  }

  if (accessState === "unavailable") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#05070d] px-4">
        <div className="w-full max-w-lg rounded-2xl border border-border/60 bg-card/80 p-6 shadow-lg">
          <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Admin service</p>
          <h1 className="mt-2 text-2xl font-semibold">Admin service unavailable</h1>
          <p className="mt-2 text-sm text-muted-foreground">
            {accessError || "Cannot reach the admin API right now."}
          </p>
          <div className="mt-6 flex gap-3">
            <Button onClick={() => void checkAccess()}>Retry</Button>
            <Button variant="outline" onClick={() => globalThis.location.assign("/")}>
              Back to site
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (accessState === "unauthenticated") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#05070d] px-4">
        <div className="w-full max-w-md rounded-2xl border border-border/60 bg-card/80 p-6 shadow-lg space-y-4">
          <div className="space-y-2">
            <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Admin login</p>
            <h1 className="text-2xl font-semibold">Sign in to continue</h1>
            <p className="text-sm text-muted-foreground">
              Enter your admin credentials to access the control plane.
            </p>
          </div>
          <form className="space-y-4" onSubmit={handleLogin}>
            <div className="space-y-2">
              <Label htmlFor="admin-login-email">Email</Label>
              <Input
                id="admin-login-email"
                type="email"
                required
                placeholder="you@example.com"
                value={loginForm.email}
                onChange={(e) => setLoginForm((prev) => ({ ...prev, email: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="admin-login-password">Password</Label>
              <Input
                id="admin-login-password"
                type="password"
                required
                value={loginForm.password}
                onChange={(e) => setLoginForm((prev) => ({ ...prev, password: e.target.value }))}
              />
            </div>
            {(loginError || accessError) && (
              <p className="text-xs text-destructive">{loginError || accessError}</p>
            )}
            <div className="flex gap-3">
              <Button type="submit" className="flex-1" disabled={loginPending}>
                {loginPending ? "Signing in..." : "Log in"}
              </Button>
              <Button type="button" variant="outline" onClick={() => globalThis.location.assign("/")}>
                Back
              </Button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  if (accessState === "forbidden") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#05070d] px-4">
        <div className="w-full max-w-lg rounded-2xl border border-border/60 bg-card/80 p-6 text-center shadow-lg">
          <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Forbidden</p>
          <h1 className="mt-2 text-2xl font-semibold text-foreground">Admin access required</h1>
          <p className="mt-2 text-sm text-muted-foreground">
            Your account is signed in, but it does not have admin privileges.
          </p>
          <div className="mt-6 flex justify-center gap-3">
            <Button variant="outline" onClick={() => globalThis.location.assign("/")}>
              Back to site
            </Button>
            <Button onClick={() => void checkAccess()}>Retry</Button>
          </div>
        </div>
      </div>
    );
  }

  if (!adminUser) {
    return null;
  }

  return (
    <AdminLayout adminUser={adminUser}>
      <Switch>
        <Route path="/admin" component={AdminOverview} />
        <Route path="/admin/users" component={AdminUsers} />
        <Route path="/admin/users/:userId">
          {() =>
            userParams?.userId ? (
              <AdminUserDetail userId={userParams.userId} />
            ) : (
              <AdminUsers />
            )
          }
        </Route>
        <Route path="/admin/runs" component={AdminRuns} />
        <Route path="/admin/runs/:runId">
          {() =>
            runParams?.runId ? (
              <AdminRunDetail runId={runParams.runId} />
            ) : (
              <AdminRuns />
            )
          }
        </Route>
        <Route path="/admin/invariants" component={AdminInvariants} />
        <Route path="/admin/support-tickets" component={AdminSupportTickets} />
        <Route component={NotFound} />
      </Switch>
    </AdminLayout>
  );
}
