"use client";

import { useState, useEffect } from "react";
import { useSortable } from "@dnd-kit/react/sortable";
import {
  ChevronRight,
  ChevronDown,
  GripVertical,
  MessageSquare,
  Calendar,
  Bot,
  Wrench,
  Shield,
  LayoutGrid,
  Sparkles,
  Music,
  Activity,
  Circle,
  BookOpen,
  Plug,
  MessageCircle,
  GitBranch,
  HardDrive,
  Server,
  FolderOpen,
  Plus,
  Orbit,
  Users,
  ArrowRightLeft,
} from "lucide-react";
import type { MenuCategory } from "@/lib/types";
import { SUBCATEGORIES } from "@/lib/constants";
import { useAgents } from "@/hooks/useAgents";
import { useAppsContext } from "@/hooks/useAppsContext";
import { useToolsMenuContext } from "@/hooks/useToolsMenuContext";

const iconMap: Record<string, typeof MessageSquare> = {
  MessageSquare,
  Calendar,
  Bot,
  Wrench,
  Shield,
  LayoutGrid,
  Sparkles,
  Music,
  Activity,
  BookOpen,
  Plug,
  MessageCircle,
  GitBranch,
  HardDrive,
  Server,
  FolderOpen,
  Orbit,
  Users,
  ArrowRightLeft,
};

interface SidebarCategoryProps {
  category: MenuCategory;
  index: number;
  active?: boolean;
  onSelect?: (id: string) => void;
  activeAgent?: string | null;
  onSelectAgent?: (agentName: string) => void;
  activeSubcategory?: string | null;
  onSelectSubcategory?: (subcategoryId: string, parentCategoryId: string) => void;
  activeCategory?: string | null;
}

export function SidebarCategory({
  category,
  index,
  active,
  onSelect,
  activeAgent,
  onSelectAgent,
  activeSubcategory,
  onSelectSubcategory,
  activeCategory,
}: SidebarCategoryProps) {
  const isExpandableCategory =
    category.id === "agents" || category.id === "tools" || !!SUBCATEGORIES[category.id];

  const [expanded, setExpanded] = useState(
    isExpandableCategory && active ? true : false
  );

  useEffect(() => {
    if (isExpandableCategory && active) {
      setExpanded(true);
    }
  }, [active, isExpandableCategory]);
  const [expandedAppsSub, setExpandedAppsSub] = useState<string | null>(null);
  const { ref, handleRef, isDragging } = useSortable({
    id: category.id,
    index,
  });
  const { agents, loading } = useAgents();
  const { hosts, categories: appCategories, loading: appsLoading } = useAppsContext();
  const { types: toolTypes, loading: toolsLoading } = useToolsMenuContext();

  const isAgentsCategory = category.id === "agents";
  const isAppsCategory = category.id === "apps";
  const isToolsCategory = category.id === "tools";
  const hasSubcategories = !!SUBCATEGORIES[category.id];
  const Icon = iconMap[category.icon] || MessageSquare;

  const handleClick = () => {
    if (isAgentsCategory || isToolsCategory || hasSubcategories) {
      setExpanded(!expanded);
      return;
    }
    if (onSelect) {
      onSelect(category.id);
    } else {
      setExpanded(!expanded);
    }
  };

  return (
    <div
      ref={ref}
      className={`select-none transition-opacity ${isDragging ? "opacity-50" : ""}`}
    >
      <div
        className={`group flex items-center gap-1 rounded-lg px-2 py-3 text-sm transition-colors md:py-1.5 ${
          active && !isAgentsCategory && !isToolsCategory && !hasSubcategories
            ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
            : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
        }`}
      >
        <div
          ref={handleRef}
          className="hidden h-6 w-6 shrink-0 cursor-grab items-center justify-center rounded text-zinc-400 opacity-0 transition-opacity group-hover:opacity-100 active:cursor-grabbing md:flex dark:text-zinc-500"
          style={{ touchAction: "none" }}
        >
          <GripVertical size={14} />
        </div>
        <button
          onClick={handleClick}
          className="flex flex-1 items-center gap-2.5"
        >
          <Icon size={16} />
          <span className="font-medium">{category.label}</span>
          {(isAgentsCategory || isToolsCategory || hasSubcategories) && (
            <span className="ml-auto text-zinc-400 dark:text-zinc-500">
              {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
            </span>
          )}
          {!isAgentsCategory && !isToolsCategory && !hasSubcategories && !onSelect && (
            <span className="ml-auto text-zinc-400 dark:text-zinc-500">
              {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
            </span>
          )}
        </button>
      </div>

      {isAgentsCategory && expanded && (
        <div className="ml-6 border-l border-zinc-200 py-1 pl-3 md:ml-11 dark:border-zinc-700">
          {loading && (
            <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
              Loading...
            </p>
          )}
          {!loading && agents.length === 0 && (
            <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
              No agents configured
            </p>
          )}
          {!loading &&
            agents.map((agent) => (
              <button
                key={agent.name}
                onClick={() => onSelectAgent?.(agent.name)}
                className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                  activeAgent === agent.name
                    ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                    : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                }`}
              >
                <Circle size={6} className="fill-current opacity-50" />
                <span className="font-medium">{agent.displayName}</span>
              </button>
            ))}
        </div>
      )}

      {isToolsCategory && expanded && (
        <div className="ml-6 border-l border-zinc-200 py-1 pl-3 md:ml-11 dark:border-zinc-700">
          {toolsLoading && (
            <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
              Loading...
            </p>
          )}
          {!toolsLoading && toolTypes.length === 0 && (
            <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
              No types configured
            </p>
          )}
          {!toolsLoading &&
            toolTypes.map((toolType) => {
              const childId = `type:${toolType.id}`;
              return (
                <button
                  key={toolType.id}
                  onClick={() => onSelectSubcategory?.(childId, "tools")}
                  className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                    activeCategory === "tools" &&
                    activeSubcategory === childId
                      ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                      : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                  }`}
                >
                  <Circle size={6} className="fill-current opacity-50" />
                  <span className="font-medium">{toolType.name}</span>
                </button>
              );
            })}
          <button
            onClick={() => onSelectSubcategory?.("type:add", "tools")}
            className="flex w-full items-center gap-2 rounded-md px-2 py-2.5 text-sm text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 md:py-1.5 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-400"
          >
            <Plus size={12} />
            <span className="font-medium">Add Type</span>
          </button>
        </div>
      )}

      {hasSubcategories && !isAppsCategory && expanded && (
        <div className="ml-6 border-l border-zinc-200 py-1 pl-3 md:ml-11 dark:border-zinc-700">
          {SUBCATEGORIES[category.id].map((sub) => {
            const SubIcon = iconMap[sub.icon] || Circle;
            return (
              <button
                key={sub.id}
                onClick={() => onSelectSubcategory?.(sub.id, category.id)}
                className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                  activeCategory === category.id && activeSubcategory === sub.id
                    ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                    : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                }`}
              >
                <SubIcon size={14} />
                <span className="font-medium">{sub.label}</span>
              </button>
            );
          })}
        </div>
      )}

      {isAppsCategory && expanded && (
        <div className="ml-6 border-l border-zinc-200 py-1 pl-3 md:ml-11 dark:border-zinc-700">
          {SUBCATEGORIES[category.id].map((sub) => {
            const SubIcon = iconMap[sub.icon] || Circle;
            const isSubExpanded = expandedAppsSub === sub.id;
            const isByHost = sub.id === "by-host";
            const isByType = sub.id === "by-type";
            const isSubActive =
              activeCategory === "apps" &&
              typeof activeSubcategory === "string" &&
              activeSubcategory.startsWith(sub.id);

            return (
              <div key={sub.id}>
                <button
                  onClick={() => {
                    setExpandedAppsSub(isSubExpanded ? null : sub.id);
                    onSelectSubcategory?.(sub.id, "apps");
                  }}
                  className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                    isSubActive
                      ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                      : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                  }`}
                >
                  <SubIcon size={14} />
                  <span className="font-medium">{sub.label}</span>
                  <span className="ml-auto text-zinc-400 dark:text-zinc-500">
                    {isSubExpanded ? (
                      <ChevronDown size={12} />
                    ) : (
                      <ChevronRight size={12} />
                    )}
                  </span>
                </button>

                {isSubExpanded && (
                  <div className="ml-4 border-l border-zinc-200 py-1 pl-3 dark:border-zinc-700">
                    {appsLoading && (
                      <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
                        Loading...
                      </p>
                    )}

                    {!appsLoading && isByHost && hosts.length === 0 && (
                      <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
                        No hosts configured
                      </p>
                    )}

                    {!appsLoading && isByType && appCategories.length === 0 && (
                      <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
                        No categories configured
                      </p>
                    )}

                    {!appsLoading &&
                      isByHost &&
                      hosts.map((host) => {
                        const childId = `by-host:${host.id}`;
                        return (
                          <button
                            key={host.id}
                            onClick={() =>
                              onSelectSubcategory?.(childId, "apps")
                            }
                            className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                              activeCategory === "apps" &&
                              activeSubcategory === childId
                                ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                                : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                            }`}
                          >
                            <Circle
                              size={6}
                              className="fill-current opacity-50"
                            />
                            <span className="font-medium">{host.name}</span>
                          </button>
                        );
                      })}

                    {!appsLoading &&
                      isByType &&
                      appCategories.map((cat) => {
                        const childId = `by-type:${cat.id}`;
                        return (
                          <button
                            key={cat.id}
                            onClick={() =>
                              onSelectSubcategory?.(childId, "apps")
                            }
                            className={`flex w-full items-center gap-2 rounded-md px-2 py-3 text-sm transition-colors md:py-1.5 ${
                              activeCategory === "apps" &&
                              activeSubcategory === childId
                                ? "bg-zinc-200 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100"
                                : "text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                            }`}
                          >
                            <Circle
                              size={6}
                              className="fill-current opacity-50"
                            />
                            <span className="font-medium">{cat.name}</span>
                          </button>
                        );
                      })}

                    <button
                      onClick={() =>
                        onSelectSubcategory?.(
                          isByHost ? "by-host:add" : "by-type:add",
                          "apps"
                        )
                      }
                      className="flex w-full items-center gap-2 rounded-md px-2 py-2.5 text-sm text-zinc-400 transition-colors hover:bg-zinc-100 hover:text-zinc-600 md:py-1.5 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-400"
                    >
                      <Plus size={12} />
                      <span className="font-medium">
                        {isByHost ? "Add Host" : "Add Category"}
                      </span>
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {!isAgentsCategory && !isToolsCategory && !hasSubcategories && !onSelect && expanded && (
        <div className="ml-6 border-l border-zinc-200 py-1 pl-3 md:ml-11 dark:border-zinc-700">
          <p className="py-1.5 text-xs text-zinc-400 dark:text-zinc-500">
            No items yet
          </p>
        </div>
      )}
    </div>
  );
}
