import { useEffect, useState } from "react";
import { Check, ChevronsUpDown, Users, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { authApi, useAuth } from "@/lib/auth";

interface UserRow {
  id: string;
  email: string;
  role: string;
  status: string;
  delta_linked: boolean;
}

/**
 * Admin-only header switcher: lists all users and lets the admin impersonate
 * any of them from the top bar. Hidden for non-admins and while already
 * impersonating (use "Exit impersonation" banner to return first).
 */
export function UserSwitcher({ collapsed = false }: { collapsed?: boolean } = {}) {
  const { user, impersonate } = useAuth();
  const [open, setOpen] = useState(false);
  const [users, setUsers] = useState<UserRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [switching, setSwitching] = useState<string | null>(null);

  const canSwitch = user?.role === "admin" && !user.impersonating;

  useEffect(() => {
    if (!open || !canSwitch) return;
    setLoading(true);
    setError(null);
    authApi
      .listUsers()
      .then((rows) => setUsers(rows))
      .catch((e) => setError(e instanceof Error ? e.message : "Failed to load users"))
      .finally(() => setLoading(false));
  }, [open, canSwitch]);

  if (!canSwitch) return null;

  async function onPick(row: UserRow) {
    if (row.id === user?.id) {
      setOpen(false);
      return;
    }
    setSwitching(row.id);
    try {
      await impersonate(row.id);
      toast.success(`Switched to ${row.email}`, { description: "Read-only session · exit from the banner" });
      setOpen(false);
    } catch (e) {
      toast.error("Switch failed", { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setSwitching(null);
    }
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          size="sm"
          className={`min-h-9 items-center gap-1.5 border-border bg-secondary/40 px-2 text-xs ${
            collapsed ? "inline-flex w-9 justify-center px-0" : "inline-flex w-full justify-start"
          }`}
          aria-label="Switch to another user account"
          title="Switch user"
        >
          <Users className="h-3.5 w-3.5 shrink-0" />
          {!collapsed && <span className="flex-1 truncate text-left">Switch user</span>}
          {!collapsed && <ChevronsUpDown className="h-3 w-3 opacity-60" />}
        </Button>
      </PopoverTrigger>
      <PopoverContent align="start" side="right" className="w-[320px] p-0">
        <Command shouldFilter>
          <CommandInput placeholder="Search email or id…" />
          <CommandList>
            {loading && (
              <div className="flex items-center justify-center gap-2 p-4 text-xs text-muted-foreground">
                <Loader2 className="h-3.5 w-3.5 animate-spin" /> Loading users…
              </div>
            )}
            {error && !loading && (
              <div className="p-4 text-xs text-destructive">
                {error}
                <div className="mt-1 text-[11px] text-muted-foreground">
                  Backend unreachable. Verify the API is running.
                </div>
              </div>
            )}
            {!loading && !error && (
              <>
                <CommandEmpty>No users match.</CommandEmpty>
                <CommandGroup heading={`${users.length} user${users.length === 1 ? "" : "s"}`}>
                  {users.map((u) => (
                    <CommandItem
                      key={u.id}
                      value={`${u.email} ${u.id}`}
                      onSelect={() => onPick(u)}
                      className="flex items-center gap-2"
                    >
                      <div className="flex min-w-0 flex-1 flex-col">
                        <span className="truncate text-sm">{u.email}</span>
                        <span className="truncate font-mono text-[10px] text-muted-foreground">
                          {u.id.slice(0, 8)} · {u.role}
                          {u.delta_linked ? " · delta" : ""}
                          {u.status !== "active" ? ` · ${u.status}` : ""}
                        </span>
                      </div>
                      {switching === u.id ? (
                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                      ) : u.id === user?.id ? (
                        <Check className="h-3.5 w-3.5 text-primary" />
                      ) : null}
                    </CommandItem>
                  ))}
                </CommandGroup>
              </>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
