import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { Button } from "../../../shared/common/ui/button";
import {
  Archive,
  Delete,
  Edit,
  Eye,
  MoreHorizontal,
  Settings,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { OrganizationActivateOrDeactivationPopup } from "./common/OrganizationActivateOrDeactivationPopup";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";

import { useTranslation } from "react-i18next";
import ManageOrganizationDrawer from "./ManageOrganizationDrawer";
import { useArchiveActions } from "@/user-management/hooks/useArchived";
interface OrganizationsActionsProps {
  rowData: OrganizationDto;
}

const OrganizationsActions: React.FC<OrganizationsActionsProps> = ({
  rowData,
}) => {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [mangeOrgConfigOpen, setManageOrgConfigOpen] = useState(false);

  const {
    activateOrganization,
    deactivateOrganization,
    isOrganizationActivating,
    isOrganizationDeactivating,
    deleteOrganization,
    isOrganizationDeleting,
  } = useOrganizations("Org");
  const { softDeleteOrganization, isArchivingOrganization } =
    useArchiveActions();
  const handleEditDetails = () => {
    setDropdownOpen(false);
    navigate(`/user-management/organizations/edit/${rowData?.id}`);
  };
  const handleViewDetails = () => {
    setDropdownOpen(false);
    navigate(`/user-management/organizations/detail/${rowData?.id}`);
  };
  const handleManageOrganization = () => {
    setDropdownOpen(false);
    setManageOrgConfigOpen(true);
  };

  const isActive = rowData.status === "Active";
  return (
    <div className="flex gap-3 align-center">
      <OrganizationActivateOrDeactivationPopup
        organizationName={rowData.name.en}
        isActive={isActive}
        onConfirm={() => {
          isActive
            ? deactivateOrganization({
                id: rowData.id,
              })
            : activateOrganization({
                id: rowData.id,
              });
        }}
        isLoading={isOrganizationActivating || isOrganizationDeactivating}
        trigger={
          isActive ? (
            <Button
              variant="outline"
              className={
                isActive
                  ? "text-red-600 dark:text-red-400 border-red-600 dark:border-red-500 hover:bg-red-50 dark:hover:bg-red-900/30"
                  : "text-primary-600 dark:text-primary-400 border-primary-600 dark:border-primary-500 hover:bg-primary-50 dark:hover:bg-primary-900/30"
              }
            >
              {t("statusBar.deactivate")}
            </Button>
          ) : (
            <Button
              variant="outline"
              size="sm"
              className={
                isActive
                  ? "text-red-600 dark:text-red-400 border-red-600 dark:border-red-500 hover:bg-red-50 dark:hover:bg-red-900/30"
                  : "text-primary-600 dark:text-primary-400 border-primary-600 dark:border-primary-500 hover:bg-primary-50 dark:hover:bg-primary-900/30"
              }
            >
              {t("statusBar.activate")}
            </Button>
          )
        }
      />
      <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
            aria-haspopup="menu"
            aria-expanded={dropdownOpen}
          >
            <MoreHorizontal className="h-4 w-4" />
            <span className="sr-only">Open menu</span>
          </Button>
        </DropdownMenuTrigger>

        <DropdownMenuContent
          align="end"
          className="w-[200px]"
          onInteractOutside={(e) => {
            // Prevent closing when interacting with dialogs
            const target = e.target as HTMLElement;
            if (!target.closest('[role="dialog"]')) {
              setDropdownOpen(false);
            }
          }}
        >
          <DropdownMenuLabel>Actions</DropdownMenuLabel>

          {/* Always show these */}
          <DropdownMenuItem onSelect={handleViewDetails}>
            <Eye className="mr-2 h-4 w-4" />
            {t("organization.viewOrganization")}
          </DropdownMenuItem>
          <DropdownMenuItem onSelect={handleManageOrganization}>
            <Settings className="mr-2 h-4 w-4" />
            {t("organization.manageOrganization", "Manage Organization")}
          </DropdownMenuItem>
          <DropdownMenuItem onSelect={handleEditDetails}>
            <Edit className="mr-2 h-4 w-4" />
            {t("organization.editOrganization")}
          </DropdownMenuItem>

          <DropdownMenuItem
            onSelect={() => {
              setDropdownOpen(false);
              softDeleteOrganization(rowData.id);
            }}
            disabled={isArchivingOrganization}
            className="text-amber-700 focus:text-amber-700"
          >
            <Archive className="mr-2 h-4 w-4" />
            {t("archive.archiveOrganization", "Archive Organization")}
          </DropdownMenuItem>
        </DropdownMenuContent>
        {mangeOrgConfigOpen && (
          <ManageOrganizationDrawer
            manageOrgConfigOpen={mangeOrgConfigOpen}
            setManageOrgConfigOpen={setManageOrgConfigOpen}
            organizationId={rowData.id}
            isUnitConfig={false}
          />
        )}
      </DropdownMenu>
    </div>
  );
};

export default OrganizationsActions;
