import { Button } from "@/client/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/client/components/ui/dropdown-menu";
import { ShimmerButton } from "@/client/components/ui/shimmer-button";
import { StatusDot } from "@/client/components/ui/status-dot";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/client/components/ui/tooltip";
import { cn } from "@/client/lib/utils";
import { ChevronDown, Info, Server, Settings } from "lucide-react";
import type { McpServer } from "mcp-use/react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { getServerDisplayName } from "@/client/utils/serverNames";
import { ServerCapabilitiesModal } from "./ServerCapabilitiesModal";
import { ServerIcon } from "./ServerIcon";

// Type alias for backward compatibility
type MCPConnection = McpServer;

interface ServerDropdownProps {
  connections: MCPConnection[];
  selectedServer: MCPConnection | undefined;
  onServerSelect: (serverId: string) => void;
  onOpenConnectionOptions: (connectionId: string | null) => void;
  mobileMode?: boolean;
}

/**
 * Render a server selection dropdown with per-connection actions to view capabilities or open connection settings.
 *
 * Renders a compact trigger in mobileMode and a full trigger in desktop mode. Selecting a connection calls `onServerSelect` only if the connection exists and its state is `"ready"`; otherwise a toast error is shown. Clicking the info action opens the ServerCapabilitiesModal for that connection. Clicking the settings action invokes `onOpenConnectionOptions` with the connection id.
 *
 * @param connections - List of available MCP connections shown in the menu
 * @param selectedServer - The currently selected connection (may be `undefined`)
 * @param onServerSelect - Callback invoked with a server id when a ready server is selected
 * @param onOpenConnectionOptions - Callback invoked with a connection id (or `null`) to open connection options
 * @param mobileMode - If `true`, render the compact/mobile variant of the dropdown
 * @returns The server dropdown React element
 */
export function ServerDropdown({
  connections,
  selectedServer,
  onServerSelect,
  onOpenConnectionOptions,
  mobileMode = false,
}: ServerDropdownProps) {
  const navigate = useNavigate();
  const [infoModalOpen, setInfoModalOpen] = useState(false);
  const [infoModalConnection, setInfoModalConnection] =
    useState<MCPConnection | null>(null);

  const handleServerSelect = (serverId: string) => {
    const server = connections.find((c) => c.id === serverId);
    if (!server || server.state !== "ready") {
      toast.error("Server is not connected and cannot be inspected");
      return;
    }
    onServerSelect(serverId);
  };

  // Mobile mode: show icon + chevron only
  if (mobileMode) {
    return (
      <div className="flex items-center gap-2">
        <div className="relative">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                className="h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5"
              >
                {selectedServer ? (
                  <ServerIcon server={selectedServer} size="md" />
                ) : (
                  <Server className="h-5 w-5" />
                )}
                <ChevronDown className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent
              className="w-[calc(100vw-2rem)] sm:w-[300px]"
              align="start"
            >
              <DropdownMenuLabel
                className="cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800"
                onClick={() => navigate("/")}
              >
                MCP Servers
              </DropdownMenuLabel>
              <DropdownMenuSeparator />
              {connections.length === 0 ? (
                <div className="px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center">
                  No servers connected. Go to the dashboard to add one.
                </div>
              ) : (
                connections.map((connection) => (
                  <DropdownMenuItem
                    key={connection.id}
                    onClick={() => handleServerSelect(connection.id)}
                    className="flex items-center gap-3"
                  >
                    <ServerIcon server={connection} size="sm" />
                    <div className="flex items-center gap-2 flex-1">
                      <div className="font-medium">
                        {getServerDisplayName(connection)}
                      </div>
                      <StatusDot status={connection.state} />
                    </div>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                        onClick={(e) => {
                          e.stopPropagation();
                          setInfoModalConnection(connection);
                          setInfoModalOpen(true);
                        }}
                      >
                        <Info className="h-3 w-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                        onClick={(e) => {
                          e.stopPropagation();
                          onOpenConnectionOptions(connection.id);
                        }}
                      >
                        <Settings className="h-3 w-3" />
                      </Button>
                    </div>
                  </DropdownMenuItem>
                ))
              )}
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => navigate("/")}>
                <span className="text-blue-600 dark:text-blue-400">
                  + Add new server
                </span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
        <ServerCapabilitiesModal
          open={infoModalOpen}
          onOpenChange={setInfoModalOpen}
          connection={infoModalConnection}
        />
      </div>
    );
  }

  // Desktop mode: show full dropdown with text
  return (
    <div className="flex items-center gap-2">
      <div className="relative">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <ShimmerButton
              className={cn(
                "min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start  text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",
                !selectedServer && "pl-4",
                selectedServer && "pr-20"
              )}
            >
              {selectedServer && (
                <ServerIcon
                  server={selectedServer}
                  size="md"
                  className="mr-2"
                />
              )}
              <div className="flex items-center gap-2 flex-1">
                <span className="truncate lg:max-w-[120px] xl:max-w-none">
                  {selectedServer
                    ? getServerDisplayName(selectedServer)
                    : "Select server to inspect"}
                </span>
                {selectedServer && (
                  <div className="flex items-center gap-2">
                    {selectedServer.error &&
                    selectedServer.state !== "ready" ? (
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              // Handle copy error functionality if needed
                            }}
                            className="w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors"
                            title="Click to copy error message"
                            aria-label="Copy error message to clipboard"
                          />
                        </TooltipTrigger>
                        <TooltipContent>
                          <p className="max-w-xs">{selectedServer.error}</p>
                        </TooltipContent>
                      </Tooltip>
                    ) : (
                      <div
                        className={`w-2 h-2 rounded-full ${
                          selectedServer.state === "ready"
                            ? "bg-emerald-600 animate-status-pulse"
                            : selectedServer.state === "failed"
                              ? "bg-rose-600 animate-status-pulse-red"
                              : "bg-yellow-500 animate-status-pulse-yellow"
                        }`}
                      />
                    )}
                  </div>
                )}
              </div>
            </ShimmerButton>
          </DropdownMenuTrigger>
          {selectedServer && (
            <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    onClick={() => {
                      setInfoModalConnection(selectedServer);
                      setInfoModalOpen(true);
                    }}
                    className="p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black"
                    aria-label="View server info"
                  >
                    <Info className="h-4 w-4" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>View server info</p>
                </TooltipContent>
              </Tooltip>
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    onClick={() => {
                      onOpenConnectionOptions(selectedServer.id);
                    }}
                    className="p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black"
                    aria-label="Edit connection settings"
                  >
                    <Settings className="h-4 w-4" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>Edit connection settings</p>
                </TooltipContent>
              </Tooltip>
            </div>
          )}
          <DropdownMenuContent
            className="w-[calc(100vw-2rem)] sm:w-[300px]"
            align="start"
          >
            <DropdownMenuLabel
              className="cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800"
              onClick={() => navigate("/")}
            >
              MCP Servers
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            {connections.length === 0 ? (
              <div className="px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center">
                No servers connected. Go to the dashboard to add one.
              </div>
            ) : (
              connections.map((connection) => (
                <DropdownMenuItem
                  key={connection.id}
                  onClick={() => handleServerSelect(connection.id)}
                  className="flex items-center gap-3"
                >
                  <ServerIcon server={connection} size="sm" />
                  <div className="flex items-center gap-2 flex-1">
                    <div className="font-medium">
                      {getServerDisplayName(connection)}
                    </div>
                    <StatusDot status={connection.state} />
                  </div>
                  <div className="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                      onClick={(e) => {
                        e.stopPropagation();
                        setInfoModalConnection(connection);
                        setInfoModalOpen(true);
                      }}
                    >
                      <Info className="h-3 w-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                      onClick={(e) => {
                        e.stopPropagation();
                        onOpenConnectionOptions(connection.id);
                      }}
                    >
                      <Settings className="h-3 w-3" />
                    </Button>
                  </div>
                </DropdownMenuItem>
              ))
            )}
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => navigate("/")}>
              <span className="text-blue-600 dark:text-blue-400">
                + Add new server
              </span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
        <ServerCapabilitiesModal
          open={infoModalOpen}
          onOpenChange={setInfoModalOpen}
          connection={infoModalConnection}
        />
      </div>
    </div>
  );
}
