import { useAppStore } from "@/stores/app-store";
import { useConnections } from "@/hooks/use-connections";
import { useMcpStatus } from "@/hooks/use-settings";
import { EnvironmentBadge } from "@/components/connections/EnvironmentBadge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

function formatDbVersion(version: string): string {
  const gpMatch = version.match(/Greenplum Database ([\d.]+)/i);
  if (gpMatch) {
    const pgMatch = version.match(/^PostgreSQL ([\d.]+)/);
    const pgVer = pgMatch ? ` (PG ${pgMatch[1]})` : "";
    return `GP ${gpMatch[1]}${pgVer}`;
  }
  return version.split(",")[0]?.replace("PostgreSQL ", "PG ") ?? version;
}

interface Props {
  rowCount?: number | null;
  executionTime?: number | null;
}

export function StatusBar({ rowCount, executionTime }: Props) {
  const { activeConnectionId, connectedIds, readOnlyMap, pgVersion } = useAppStore();
  const { data: connections } = useConnections();
  const { data: mcpStatus } = useMcpStatus();

  const activeConn = connections?.find((c) => c.id === activeConnectionId);
  const isConnected = activeConnectionId
    ? connectedIds.has(activeConnectionId)
    : false;

  return (
    <div className="tusk-status-bar flex h-6 items-center justify-between px-3 text-[11px] text-muted-foreground">
      <div className="flex items-center gap-3">
        <span className="flex items-center gap-1.5">
          {activeConn?.color ? (
            <span
              className="inline-block h-2 w-2 rounded-full ring-1 ring-white/10"
              style={{ backgroundColor: activeConn.color }}
            />
          ) : (
            <span
              className={`inline-block h-2 w-2 rounded-full ${
                isConnected
                  ? "bg-success ring-2 ring-success/25"
                  : "bg-muted-foreground/30"
              }`}
            />
          )}
          <span className="font-medium">
            {activeConn ? activeConn.name : "No connection"}
          </span>
          <EnvironmentBadge environment={activeConn?.environment} size="sm" />
        </span>
        {isConnected && activeConnectionId && (
          <span
            className={`rounded px-1 py-px text-[10px] font-semibold tracking-wide ${
              (readOnlyMap[activeConnectionId] ?? true)
                ? "bg-warning/10 text-warning"
                : "bg-success/10 text-success"
            }`}
          >
            {(readOnlyMap[activeConnectionId] ?? true) ? "READ" : "WRITE"}
          </span>
        )}
        {pgVersion && (
          <span className="hidden text-muted-foreground/60 sm:inline font-mono text-[10px]">
            {formatDbVersion(pgVersion)}
          </span>
        )}
      </div>
      <div className="flex items-center gap-3">
        {rowCount != null && (
          <span className="font-mono">
            {rowCount.toLocaleString()} <span className="text-muted-foreground/50">rows</span>
          </span>
        )}
        {executionTime != null && (
          <span className="font-mono">
            {executionTime} <span className="text-muted-foreground/50">ms</span>
          </span>
        )}
        <Tooltip>
          <TooltipTrigger asChild>
            <span className="flex items-center gap-1.5 cursor-default">
              <span
                className={`inline-block h-1.5 w-1.5 rounded-full transition-colors ${
                  mcpStatus?.running
                    ? "bg-success ring-2 ring-success/25"
                    : "bg-muted-foreground/20"
                }`}
              />
              <span className="tracking-wide">MCP</span>
            </span>
          </TooltipTrigger>
          <TooltipContent side="top">
            <p className="text-xs">
              MCP Server {mcpStatus?.running ? `running on :${mcpStatus.port}` : "stopped"}
            </p>
          </TooltipContent>
        </Tooltip>
      </div>
    </div>
  );
}
