import { useNavigate } from "@tanstack/react-router";
import { Globe, PlusCircle } from "lucide-react";
import { useAtomValue } from "jotai";
import { selectedConnectorIdAtom } from "@/atoms/appAtoms";
import {
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuItem,
} from "@/components/ui/sidebar";
import { Button } from "@/components/ui/button";
import { useLoadConnectors } from "@/hooks/useLoadConnectors";
import type { ConnectorSummary } from "@/ipc/types";
import { formatDistanceToNow } from "date-fns";
import { useTranslation } from "react-i18next";

export function ConnectorList({ show }: { show?: boolean }) {
  const { t } = useTranslation("home");
  const navigate = useNavigate();
  const selectedConnectorId = useAtomValue(selectedConnectorIdAtom);
  const { connectors, loading, error } = useLoadConnectors();

  if (!show) {
    return null;
  }

  return (
    <SidebarGroup
      className="overflow-y-auto h-[calc(100vh-112px)]"
      data-testid="connector-list-container"
    >
      <SidebarGroupLabel>{t("connectors.list.title")}</SidebarGroupLabel>
      <SidebarGroupContent>
        <div className="flex flex-col space-y-2">
          <Button
            onClick={() => navigate({ to: "/connectors", search: {} })}
            variant="outline"
            className="flex items-center justify-start gap-2 mx-2 py-2"
          >
            <PlusCircle size={16} />
            <span>{t("connectors.list.import")}</span>
          </Button>

          {loading ? (
            <div className="py-2 px-4 text-sm text-gray-500">
              {t("connectors.list.loading")}
            </div>
          ) : error ? (
            <div className="py-2 px-4 text-sm text-red-500">
              {t("connectors.list.error")}
            </div>
          ) : connectors.length === 0 ? (
            <div className="py-2 px-4 text-sm text-gray-500">
              {t("connectors.list.empty")}
            </div>
          ) : (
            <SidebarMenu className="space-y-1" data-testid="connector-list">
              {connectors.map((connector: ConnectorSummary) => (
                <SidebarMenuItem key={connector.id} className="mb-1 relative">
                  <div
                    className="flex w-[206px] items-center"
                    title={connector.name}
                  >
                    <Button
                      variant="ghost"
                      onClick={() =>
                        navigate({
                          to: "/connectors",
                          search: { id: connector.id },
                        })
                      }
                      className={`justify-start w-full text-left py-3 hover:bg-sidebar-accent/80 ${
                        selectedConnectorId === connector.id
                          ? "bg-sidebar-accent text-sidebar-accent-foreground"
                          : ""
                      }`}
                    >
                      <div className="flex flex-col w-4/5">
                        <div className="flex items-center gap-2">
                          <Globe size={12} className="flex-shrink-0" />
                          <span className="truncate">{connector.name}</span>
                        </div>
                        <span className="text-xs text-gray-500 truncate">
                          {connector.endpointCount}{" "}
                          {t("connectors.endpointsLabel")} •{" "}
                          {connector.lastSyncedAt
                            ? formatDistanceToNow(
                                new Date(connector.lastSyncedAt),
                                {
                                  addSuffix: true,
                                },
                              )
                            : t("connectors.neverSynced")}
                        </span>
                      </div>
                    </Button>
                  </div>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          )}
        </div>
      </SidebarGroupContent>
    </SidebarGroup>
  );
}
