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";

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

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

export default function AdminPage() {
  const [accessState, setAccessState] = useState<AccessState>("loading");
  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 () => {
    try {
      const res = await fetch("admin/overview", { credentials: "include" });
      if (res.status === 401) {
        setAccessState("unauthenticated");
        return;
      }
      if (res.status === 403) {
        setAccessState("forbidden");
        return;
      }
      if (!res.ok) {
        setAccessState("forbidden");
        return;
      }
      setAccessState("allowed");
    } catch {
      setAccessState("forbidden");
    }
  }, []);

  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 (err) {
      const message = err instanceof Error ? err.message : "Login failed";
      setLoginError(message);
      setAccessState("unauthenticated");
    } finally {
      setLoginPending(false);
    }
  };

  if (accessState === "loading") {
    return <div className="min-h-screen text-muted-foreground">Loading admin...</div>;
  }

  if (accessState === "unauthenticated") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background 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 && <p className="text-xs text-destructive">{loginError}</p>}
            <Button type="submit" className="w-full" disabled={loginPending}>
              {loginPending ? "Signing in..." : "Log in"}
            </Button>
          </form>
        </div>
      </div>
    );
  }

  if (accessState === "forbidden") {
    return (
      <div className="min-h-screen flex items-center justify-center text-muted-foreground">
        <div className="space-y-3 text-center">
          <h1 className="text-xl font-semibold text-foreground">Admin access required</h1>
          <p className="text-sm">
            Your account is signed in but does not have admin privileges.
          </p>
        </div>
      </div>
    );
  }

  return (
    <AdminLayout>
      <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>
  );
}
