import { cn } from "@/super-admin/lib/utils";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";
import { useState } from "react";
import { MoreHorizontal, Plus } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";

interface Organization {
  id: string;
  name: { am: string; en: string };
  units?: any[];
  isExpanded?: boolean;
}

interface OrganizationListProps {
  selectedOrgId: string;
  onSelectOrganization: (orgId: string) => void;
  organizations: Organization[];
  isLoading: boolean;
  searchQuery?: string;
  onCreateUnit?: (orgId: string) => void;
  canCreateUnitForOrg?: (orgId: string) => boolean;
}

export const OrganizationList = ({
  selectedOrgId,
  onSelectOrganization,
  organizations = [],
  isLoading = false,
  searchQuery = "",
  onCreateUnit,
  canCreateUnitForOrg,
}: OrganizationListProps) => {
  const localizedName = useLocalizedName();
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);

  const filteredOrganizations = organizations.filter((org) => {
    if (!searchQuery) return true;
    const name = localizedName(org.name);
    return name.toLowerCase().includes(searchQuery.toLowerCase());
  });

  return (
    <div className="flex flex-col gap-2 min-h-[400px]">
      {isLoading ? (
        <div className="flex justify-center items-center h-full text-gray-500 dark:text-gray-400">
          <p>{t("organization.loading")}</p>
        </div>
      ) : filteredOrganizations.length > 0 ? (
        filteredOrganizations.map((org) => {
          const canCreate = canCreateUnitForOrg
            ? canCreateUnitForOrg(org.id)
            : false;
          return (
            <div
              key={org.id}
              className={cn(
                "flex items-center justify-between p-2 rounded-md cursor-pointer group",
                org.id === selectedOrgId
                  ? "bg-primary-50 text-primary-700 dark:bg-primary-900/30 dark:text-primary-300"
                  : "hover:bg-primary-50 hover:text-primary-700 dark:hover:bg-primary-900/30 dark:hover:text-primary-300 text-gray-800 dark:text-gray-200",
              )}
              onClick={() => onSelectOrganization(org.id)}
            >
              <div className="flex-1">
                <span
                  className={cn(
                    "text-sm",
                    org.id === selectedOrgId ? "font-medium" : "",
                  )}
                >
                  {localizedName(org.name)}
                </span>
              </div>
              {onCreateUnit && (
                <DropdownMenu
                  open={openMenuId === org.id}
                  onOpenChange={(open) => setOpenMenuId(open ? org.id : null)}
                >
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 dark:hover:bg-gray-700"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <MoreHorizontal className="h-4 w-4 dark:text-gray-400" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent
                    align="end"
                    className="w-[180px] dark:bg-gray-700 dark:border-gray-600"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <DropdownMenuLabel className="dark:text-gray-200">
                      Actions
                    </DropdownMenuLabel>
                    <DropdownMenuItem
                      disabled={!canCreate}
                      onClick={() => {
                        setOpenMenuId(null);
                        onCreateUnit(org.id);
                      }}
                      className="dark:text-gray-200 dark:hover:bg-gray-600"
                    >
                      <Plus className="mr-2 h-4 w-4" />
                      {t("contentManagement.createUnit", "Create Unit")}
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
          );
        })
      ) : (
        <div className="flex flex-col items-center justify-center h-full text-gray-400 dark:text-gray-500">
          <p className="text-sm">{t("contentManagement.noOrg")}</p>
        </div>
      )}
    </div>
  );
};
