import { cn } from "@/super-admin/lib/utils";
import { DepartmentActions } from "../actions/DepartmentActions";
import { useState } from "react";
import { Entity, Name } from "../types";
import {
  ChevronDown,
  ChevronRight,
  Dot,
  Users,
  UserPlus,
  FolderPlus,
  UserCog,
  Loader2,
  FolderX,
} from "lucide-react";
import { PositionDto } from "@/user-management/dto/positions/positionDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";

interface Department {
  id: string;
  name: Name;
  positions?: Position[];
  children?: Department[];
  isExpanded?: boolean;
  parentDepartmentId?: string;
  userCount?: number;
}

interface Position {
  id: string;
  name: {
    am: string;
    en: string;
  };
  isExpanded?: boolean;
}

interface DepartmentListProps {
  unitId: string;
  selectedDepartmentId: string;
  onSelectDepartment: (departmentId: string, departments: Entity[]) => void;
  departments: Department[];
  positions: PositionDto[];
  isLoading: boolean;
  searchQuery?: string;
  onAddUser?: (departmentId: string, departmentName: string) => void;
  onViewUsers?: (departmentId: string) => void;
  onAddPosition?: (departmentId: string, positionType: string) => void;
  onAddSubDepartment?: (departmentId: string, departmentName: string) => void;
  onDelegate?: (departmentId: string) => void;
  onAssignUser?: (departmentId: string, departmentName: string) => void;
  onEditDepartment?: (departmentId: string, departmentName: string) => void;
  onDeleteDepartment?: (departmentId: string, departmentName: string) => void;
  onArchiveDepartment?: (departmentId: string, departmentName: string) => void;
  onMoveDepartment?: (departmentId: string, departmentName: string) => void;
}

export const DepartmentList = ({
  unitId,
  selectedDepartmentId,
  onSelectDepartment,
  departments = [],
  positions,
  isLoading = false,
  searchQuery = "",
  onAddUser,
  onViewUsers,
  onAddPosition,
  onAddSubDepartment,
  onEditDepartment,
  onDeleteDepartment,
  onArchiveDepartment,
  onDelegate,
  onAssignUser,
  onMoveDepartment,
}: DepartmentListProps) => {
  const [hoveredId, setHoveredId] = useState<string | null>(null);
  const [expandedState, setExpandedState] = useState<Record<string, boolean>>(
    {}
  );
  const localizedName = useLocalizedName();

  // Filter departments based on search query
  const filterDepartments = (depts: Department[]): Department[] => {
    if (!searchQuery) return depts;

    return depts
      .filter((dept) => {
        const name = localizedName(dept.name);
        const matchesName = name
          .toLowerCase()
          .includes(searchQuery.toLowerCase());

        // Also check if any child departments match
        const hasMatchingChildren =
          dept.children && dept.children.length > 0
            ? filterDepartments(dept.children).length > 0
            : false;

        return matchesName || hasMatchingChildren;
      })
      .map((dept) => ({
        ...dept,
        children: dept.children ? filterDepartments(dept.children) : undefined,
      }));
  };

  const filteredDepartments = filterDepartments(departments);
  const toggleExpand = (id: string) => {
    setExpandedState((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  const renderDepartment = (dept: Department, level = 0) => {
    const isSelected = dept.id === selectedDepartmentId;
    const isHovered = hoveredId === dept.id;
    const isExpanded = expandedState[dept.id] ?? dept.isExpanded;
    const departmentName = localizedName(dept.name);
    const hasChildren =
      (dept.children?.length ?? 0) > 0 || (dept.positions?.length ?? 0) > 0;

    return (
      <div
        key={dept.id}
        className={cn("flex flex-col gap-1 group", level > 0 && "ml-4")}
      >
        <div
          className={cn(
            "flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700",
            isSelected && "bg-gray-100 dark:bg-gray-700",
            !isSelected && "text-gray-800 dark:text-gray-200"
          )}
          onClick={() => onSelectDepartment(dept.id, [])}
        >
          <div className="flex min-w-0 flex-1 items-center gap-2">
            {hasChildren ? (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  toggleExpand(dept.id);
                }}
                className="w-4 h-4 flex shrink-0 items-center justify-center"
              >
                {isExpanded ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronRight className="w-4 h-4" />
                )}
              </button>
            ) : (
              <Dot className="w-4 h-4 shrink-0" />
            )}
            <span className="min-w-0 flex-1 truncate" title={departmentName}>
              {departmentName}
            </span>
          </div>
          <DepartmentActions
            department={dept}
            positions={positions}
            onAddUser={onAddUser}
            onViewUsers={onViewUsers}
            onAddPosition={onAddPosition}
            onAddSubDepartment={onAddSubDepartment}
            onDelegate={onDelegate}
            onAssignUser={onAssignUser}
            onEditDepartment={onEditDepartment}
            onDeleteDepartment={onDeleteDepartment}
            onArchiveDepartment={onArchiveDepartment}
            onMoveDepartment={onMoveDepartment}
          />
        </div>
        {isExpanded && hasChildren && (
          <div>
            {dept.children?.map((child) => renderDepartment(child, level + 1))}
            {dept.positions?.map((pos) => {
              const positionName = pos.name.am || pos.name.en;
              return (
                <div
                  key={pos.id}
                  className={cn(
                    "flex items-center gap-2 text-sm py-1 pl-8 border-l-2 border-primary-100 dark:border-primary-800 ml-4 text-gray-800 dark:text-gray-200",
                    expandedState[pos.id] ? "bg-primary-50 dark:bg-primary-900/20" : "hover:bg-primary-50 dark:hover:bg-primary-900/20"
                  )}
                  onClick={() => toggleExpand(pos.id)}
                >
                  <Dot className="w-4 h-4 shrink-0 text-gray-400 dark:text-gray-500" />
                  <span className="min-w-0 flex-1 truncate" title={positionName}>
                    {positionName}
                  </span>
                  {isHovered && (
                    <div className="flex shrink-0 gap-2 pr-2">
                      <UserPlus
                        className="w-4 h-4 text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400"
                        onClick={(e) => {
                          e.stopPropagation();
                          onAddUser?.(pos.id, pos.name.en);
                        }}
                      />
                      <FolderPlus
                        className="w-4 h-4 text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400"
                        onClick={(e) => {
                          e.stopPropagation();
                          onAddPosition?.(pos.id, "sub");
                        }}
                      />
                      <UserCog
                        className="w-4 h-4 text-gray-500 dark:text-gray-400 hover:text-purple-600 dark:hover:text-purple-400"
                        onClick={(e) => {
                          e.stopPropagation();
                          onDelegate?.(pos.id);
                        }}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="flex flex-col gap-1 min-h-[400px]">
      {isLoading ? (
        <div className="flex justify-center items-center h-full gap-2 text-gray-500 dark:text-gray-400">
          <Loader2 className="w-4 h-4 animate-spin" />
          <p>{t("organization.loading")}</p>
        </div>
      ) : filteredDepartments.length > 0 ? (
        filteredDepartments.map((dept) => renderDepartment(dept))
      ) : (
        <div className="flex flex-col items-center justify-center h-full gap-2 text-gray-400 dark:text-gray-500">
          <FolderX className="w-6 h-6" />
          <p className="text-sm">
            {searchQuery
              ? t("search.noResults")
              : t("userIncoming.No Department")}
          </p>
        </div>
      )}
    </div>
  );
};
