import { useAppStore } from "@/stores/app-store";
import { useConnections } from "@/hooks/use-connections";
import { ScrollArea } from "@/components/ui/scroll-area";
import { X, Table2, Code, Columns, Sparkles } from "lucide-react";

export function TabBar() {
  const { tabs, activeTabId, setActiveTabId, closeTab } = useAppStore();
  const { data: connections } = useConnections();

  if (tabs.length === 0) return null;

  const iconMap: Record<string, React.ReactNode> = {
    query: <Code className="h-3 w-3" />,
    table: <Table2 className="h-3 w-3" />,
    structure: <Columns className="h-3 w-3" />,
    chat: <Sparkles className="h-3 w-3" />,
  };

  return (
    <div className="border-b border-border/40" style={{ background: "var(--card)" }}>
      <ScrollArea>
        <div className="flex">
          {tabs.map((tab) => {
            const isActive = activeTabId === tab.id;
            const tabColor = connections?.find((c) => c.id === tab.connectionId)?.color;

            return (
              <div
                key={tab.id}
                className={`group relative flex h-8 cursor-pointer items-center gap-1.5 px-3 text-xs transition-colors ${
                  isActive
                    ? "bg-background text-foreground tusk-tab-active"
                    : "text-muted-foreground hover:bg-accent/30 hover:text-foreground/80"
                }`}
                onClick={() => setActiveTabId(tab.id)}
              >
                {tabColor && (
                  <span
                    className="h-2 w-2 shrink-0 rounded-full"
                    style={{ backgroundColor: tabColor }}
                  />
                )}
                <span className="opacity-60">{iconMap[tab.type]}</span>
                <span className="max-w-[150px] truncate font-medium">
                  {tab.title}
                  {tab.database && (
                    <span className="ml-1 text-[10px] font-normal text-muted-foreground/60">
                      {tab.database}
                    </span>
                  )}
                </span>
                <button
                  className="ml-1 rounded-sm p-0.5 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-60 hover:!opacity-100"
                  onClick={(e) => {
                    e.stopPropagation();
                    closeTab(tab.id);
                  }}
                >
                  <X className="h-3 w-3" />
                </button>

                {/* Right separator between tabs */}
                {!isActive && (
                  <div className="absolute right-0 top-1.5 bottom-1.5 w-px bg-border/30" />
                )}
              </div>
            );
          })}
        </div>
      </ScrollArea>
    </div>
  );
}
