import { useState, useMemo, useEffect } from "react";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import { Button } from "@/shared/common/ui/button";
import { AdvancedTable } from "../../../shared/common/ui/table/AdvancedTable";
import { OrganizationsColumnDefn } from "./OrganizationsColumnDefn";
import { Link } from "react-router-dom";
import { Loader, Plus, ChevronDown, ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../../../shared/common/ui/card";
import { WithPermission } from "@/shared/hooks/useHas";
import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import { useLocalizedName } from "@/shared/common/localizedName";

export default function Organizations() {
  const [pageIndex, setPageIndex] = useState(0); // starts at 0
  const [expandedParents, setExpandedParents] = useState<Set<string>>(
    new Set()
  );
  const [searchTerm, setSearchTerm] = useState("");
  const pageSize = 10; // 10 organizations per page

  // Reset to first page whenever the search term changes so users land on
  // the first page of matches instead of an empty later page.
  useEffect(() => {
    setPageIndex(0);
  }, [searchTerm]);
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const { organizationsResponse, isLoading, refetch } = useOrganizations(
    "Org",
    {
      take: 1000, // Get all organizations to build hierarchy
      skip: 0,
      orderBy: "createdAt",
      order: "createdAt:Desc",
    }
  );

  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  const toggleExpanded = (parentId: string) => {
    setExpandedParents((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(parentId)) {
        newSet.delete(parentId);
      } else {
        newSet.add(parentId);
      }
      return newSet;
    });
  };

  // Create a map of organizations for quick parent lookup
  const organizationMap = useMemo(() => {
    const map = new Map<string, OrganizationDto>();
    (organizationsResponse?.items || []).forEach((org) => {
      map.set(org.id, org);
    });
    return map;
  }, [organizationsResponse?.items]);

  // Build hierarchical structure for dropdown display
  const buildHierarchy = (orgs: OrganizationDto[]) => {
    const root: OrganizationDto[] = [];
    const children = new Map<string, OrganizationDto[]>();

    // Separate root and children
    orgs.forEach((org) => {
      if (org.parentId) {
        if (!children.has(org.parentId)) {
          children.set(org.parentId, []);
        }
        children.get(org.parentId)!.push(org);
      } else {
        root.push(org);
      }
    });

    return { root, children };
  };

  const allOrganizations = useMemo(
    () => organizationsResponse?.items || [],
    [organizationsResponse?.items],
  );
  const { root, children } = buildHierarchy(allOrganizations);

  // When searching, match across ALL orgs (including children) by name in
  // either language and display the results as a flat list. When not
  // searching, fall back to the normal hierarchical view of root orgs.
  const trimmedSearch = searchTerm.trim().toLowerCase();
  const isSearching = trimmedSearch.length > 0;

  const searchMatches = useMemo(() => {
    if (!isSearching) return [] as OrganizationDto[];
    return allOrganizations.filter(
      (org) =>
        (org.name?.en || "").toLowerCase().includes(trimmedSearch) ||
        (org.name?.am || "").toLowerCase().includes(trimmedSearch),
    );
  }, [allOrganizations, isSearching, trimmedSearch]);

  // The base list to paginate over — full root in normal mode, the flat set
  // of matched orgs in search mode.
  const baseList = isSearching ? searchMatches : root;

  // Paginate
  const startIndex = pageIndex * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedBase = baseList.slice(startIndex, endIndex);

  // Build the final organizations list
  const organizations = useMemo(() => {
    const result: (OrganizationDto & {
      isChild?: boolean;
      parentName?: string;
    })[] = [];

    if (isSearching) {
      // Flat search results — annotate with parent name if it's a child
      paginatedBase.forEach((org) => {
        const parent = org.parentId ? organizationMap.get(org.parentId) : null;
        result.push({
          ...org,
          isChild: !!org.parentId,
          parentName: parent ? parent.name.en : undefined,
        });
      });
      return result;
    }

    paginatedBase.forEach((parent) => {
      // Add parent organization
      result.push(parent);

      // Add children if parent is expanded
      if (expandedParents.has(parent.id)) {
        const parentChildren = children.get(parent.id) || [];
        parentChildren.forEach((child) => {
          result.push({
            ...child,
            isChild: true,
            parentName: parent.name.en,
          });
        });
      }
    });

    return result;
  }, [paginatedBase, children, expandedParents, isSearching, organizationMap]);

  // Create custom column definition with expandable functionality
  const customColumns = useMemo(() => {
    return OrganizationsColumnDefn.map((column) => {
      if ("accessorKey" in column && column.accessorKey === "name.en") {
        return {
          ...column,
          cell: ({ row }: any) => {
            const org = row.original;
            const isChild = org.isChild || false;
            const parentName = org.parentName;
            const hasChildren = children.has(org.id);
            const isExpanded = expandedParents.has(org.id);

            return (
              <div className="flex items-center gap-2 min-w-0">
                {hasChildren && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 w-6 p-0 flex-shrink-0"
                    onClick={() => toggleExpanded(org.id)}
                  >
                    {isExpanded ? (
                      <ChevronDown className="h-4 w-4" />
                    ) : (
                      <ChevronRight className="h-4 w-4" />
                    )}
                  </Button>
                )}

                <div className="font-medium flex items-center gap-2 min-w-0 flex-1 overflow-hidden">
                  {isChild && (
                    <span className="text-gray-400 dark:text-gray-500 flex-shrink-0">└─</span>
                  )}
                  <div className="min-w-0 flex-1">
                    <div className="truncate" title={org.name.en}>
                      {localizedName(org.name)}
                    </div>
                    {parentName && (
                      <div
                        className="text-sm text-gray-500 dark:text-gray-400 font-normal truncate"
                        title={`under ${parentName}`}
                      >
                        (under {parentName})
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          },
        };
      }
      return column;
    });
  }, [children, expandedParents, localizedName]);

  if (isLoading) {
    return (
      <div>
        <Loader />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <Card className="col-span-2 shadow-none border-none bg-transparent px-0">
        <CardHeader className="flex flex-row justify-between items-center px-0">
          <CardTitle className="text-xl font-semibold ">
            {t("organization.organizations")}
          </CardTitle>
        </CardHeader>
        <CardContent className="px-0">
          <AdvancedTable
            columns={customColumns}
            data={organizations}
            tableName="Organizations"
            toolBarPosition="right"
            itemCount={baseList.length}
            pageSize={pageSize}
            onGlobalFilterChange={setSearchTerm}
            extraToolbar={
              <WithPermission
                perms={["create:organization", "activate:organization"]}
              >
                <Link to="/user-management/organizations/new">
                  <Button className="px-5 py-2 rounded-md text-sm font-medium shadow-md">
                    <Plus className="w-4 h-4 mr-2" />
                    {t("organization.newOrganization")}
                  </Button>
                </Link>
              </WithPermission>
            }
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={() => handlePageChange(pageIndex + 1)}
            prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
            refresh={refetch}
          />
        </CardContent>
      </Card>
    </div>
  );
}
