import { Button, getActionButtonVariant } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useState } from "react";
import {
  EllipsisVertical,
  ForwardIcon,
  Key,
  Unlock,
  Trash2,
  SquareCheckBig,
  SquarePen,
  Download,
  AlertTriangle,
  Mail,
  Send,
  MessageSquareText,
  Users,
} from "lucide-react";
import { useNavigate, useSearchParams } from "react-router-dom";

import ForwardRecord from "./forwardRecord";
import DeleteRecord from "./deleteRecord";
import ApproveRecord from "./approveRecord";
import DownloadRecord from "./downloadRecords";
import ShareViaEmail from "./shareViaEmail";
import SendRecord from "./sendRecord";
import CollaborationCommentsDialog from "@/record-management/components/collaborations/CollaborationCommentsDialog";
import TeamRecordCollaborationDetailsDialog from "./TeamRecordCollaborationDetailsDialog";

import { useUserDetail } from "../hooks/useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUserRecords } from "../hooks/useUserRecords";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { useCollaborationByRecordId } from "../hooks/useMyCollaborations";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { MeDto } from "@/shared/dto/user/meDto";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import IncomingInstanceDetail from "../userIncoming/IncomingInstanceDetail";

interface UserRecordProps {
  rowData: RecordDto;
  refetchTable?: () => void;
  isSecretary?: boolean;
  isSelf?: boolean;
  pageIndex?: number;
  fromTable: boolean;
  waitForAllCollaboratorsBeforeAction?: boolean;
  onApproveClick?: (row: RecordDto) => void;
  isDropdownOpen?: boolean;
  onDropdownOpenChange?: (open: boolean) => void;
  dropdownId?: string;
}

const UserRecordsActions: React.FC<UserRecordProps> = ({
  rowData,
  refetchTable,
  isSecretary,
  isSelf,
  pageIndex,
  fromTable,
  onApproveClick,
  waitForAllCollaboratorsBeforeAction,
  isDropdownOpen = false,
  onDropdownOpenChange,
  dropdownId = "",
}) => {
  const { userDetails, unFilteredUserDetails, selectedPositionId } =
    useAuthUser();
  const { checkHaveParent } = useUserDetail(userDetails as MeDto);
  const allPositions =
    unFilteredUserDetails?.employee?.flatMap((emp) => emp.positions) || [];

  const currentPosition = allPositions.find(
    (pos) =>
      pos.id === selectedPositionId ||
      pos.employeePositionId === selectedPositionId,
  );

  const {
    makeSecureRecord,
    unMakeSecureRecord,
    markUrgentRecord,
    unMarkUrgentRecord,
    forceDispatchCollaborator,
    isForceDispatchingCollaborator,
  } = useUserRecords(); // ✅ add urgent actions in hook

  const { data: unitConfigData } = useUnitConfiguration(rowData.unitId, {
    enabled: !!rowData.unitId,
  });
  const allowEditOnCollaboration =
    unitConfigData?.data?.items?.[0]?.allowEditOnCollaboration ?? false;

  // Fetch collaboration data if waitForAllCollaboratorsBeforeAction is enabled
  const { data: collaborationData } = useCollaborationByRecordId(rowData.id, {
    enabled:
      waitForAllCollaboratorsBeforeAction && rowData.initiationType === "team",
  });

  // Check if all collaborators have completed their actions
  const collaborationItems = collaborationData?.items ?? [];
  const hasPendingCollaborators = collaborationItems.some((item: any) => {
    const hasNoAction =
      !item.signStatus || item.signStatus === "draft" || item.signStatus === "";
    return hasNoAction;
  });
  const allCollaboratorsCompleted =
    !waitForAllCollaboratorsBeforeAction ||
    rowData.initiationType !== "team" ||
    !hasPendingCollaborators;

  const [isOpenSecure, setIsOpenSecure] = useState(false);
  const [isOpenUrgent, setIsOpenUrgent] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showDownloadDialog, setShowDownloadDialog] = useState(false);
  const [showForward, setShowForward] = useState(false);
  const [showApprove, setShowApprove] = useState(false);
  const [showForceDispatchDialog, setShowForceDispatchDialog] = useState(false);
  const [showShareEmail, setShowShareEmail] = useState(false);
  const [showSend, setShowSend] = useState(false);
  const [showCollaborationComments, setShowCollaborationComments] =
    useState(false);
  const [showCollaborationDetails, setShowCollaborationDetails] =
    useState(false);
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { t } = useTranslation();
  const permissionKeys = currentPosition?.permissions?.map((p) => p.key) || [];

  const getOutgoingListUrl = () => {
    const params = new URLSearchParams();
    const page =
      searchParams.get("page") || (pageIndex ? String(pageIndex) : "");
    const view = searchParams.get("view");

    if (page) params.set("page", page);
    if (view === "parent") params.set("view", view);

    const queryString = params.toString();
    return `/record-management/userRecords${
      queryString ? `?${queryString}` : ""
    }`;
  };
  const secretaryView = isSelf ? "" : "parent";
  const employeePositionId =
    userDetails?.employee?.flatMap(
      (emp) => emp?.positions?.map((pos) => pos.employeePositionId) || [],
    ) || [];
  const employeePositionDelegatorId =
    userDetails?.employee?.flatMap(
      (emp) => emp?.positions?.map((pos) => pos.delegatorId) || [],
    ) || [];
  const initatorId = rowData?.initiator?.id;
  const shouldShowAction: boolean =
    employeePositionId.includes(initatorId) ||
    employeePositionDelegatorId.includes(initatorId);
  const handleEditClick = () => {
    
    navigate(`/record-management/userRecords/editUserRecord/${rowData?.id}`);
  };
  const handleViewDetails = () => {
    
    const baseUrl = `/record-management/userRecords/viewRecord/${rowData?.id}/?page=${pageIndex}`;
    const url = secretaryView === "parent" ? `${baseUrl}&view=parent` : baseUrl;
    navigate(url);
  };

  const handleForwardClick = () => {
    
    if (!allCollaboratorsCompleted && waitForAllCollaboratorsBeforeAction) {
      toast.error(
        t(
          "userRecord.waitingForCollaborators",
          "Cannot forward: Waiting for all collaborators to complete their actions",
        ),
      );
      return;
    }
    setShowForward(true);
  };

  const handleDeleteClick = () => {
    
    setShowDeleteDialog(true);
  };

  const handleApproveClick = () => {
    
    if (!allCollaboratorsCompleted && waitForAllCollaboratorsBeforeAction) {
      toast.error(
        t(
          "userRecord.waitingForCollaborators",
          "Cannot approve: Waiting for all collaborators to complete their actions",
        ),
      );
      return;
    }
    if (onApproveClick) {
      onApproveClick(rowData);
    } else {
      setShowApprove(true);
    }
  };

  const handleSendClick = () => {
    
    setShowSend(true);
  };

  const handleDownloadClick = () => {
    
    setShowDownloadDialog(true);
  };

  const handleForceDispatchClick = () => {
    
    setShowForceDispatchDialog(true);
  };

  const handleShareEmailClick = () => {
    
    setShowShareEmail(true);
  };

  const handleCollaborationCommentsClick = () => {
    
    setShowCollaborationComments(true);
  };

  const handleCollaborationDetailsClick = () => {
    
    setShowCollaborationDetails(true);
  };

  /** ✅ Secure/Unsecure confirm */
  const handleSecureConfirm = () => {
    if (isSecure) {
      unMakeSecureRecord(
        { id: rowData.id },
        {
          onSuccess: () =>
            toast.success(t("userRecord.recordUnsecuredSuccess")),
        },
      );
    } else {
      makeSecureRecord(
        { id: rowData.id },
        {
          onSuccess: () => toast.success(t("userRecord.recordSecuredSuccess")),
        },
      );
    }
    setIsOpenSecure(false);
  };

  /** ✅ Urgent/Unmark Urgent confirm */
  const handleUrgentConfirm = () => {
    if (isUrgent) {
      unMarkUrgentRecord(
        { id: rowData.id },
        {
          onSuccess: () =>
            toast.success(t("userRecord.recordUrgencyClearedSuccess")),
        },
      );
    } else {
      markUrgentRecord(
        { id: rowData.id },
        {
          onSuccess: () =>
            toast.success(t("userRecord.recordMarkedUrgentSuccess")),
        },
      );
    }
    setIsOpenUrgent(false);
  };

  /**  Determine UI visibility */
  const actionsVisible =
    rowData.statusKey === "Draft" ||
    rowData.statusKey === "Adjustment" ||
    rowData.statusKey === "Returned" ||
    rowData.statusKey === "Team Rejected" ||
    rowData.statusKey === "Team Adjusted" ||
    rowData.statusKey === "Team Signature";
  // Once a collaboration letter is rejected (hard reject or team send-back),
  // Approve must disappear so the creator can't re-submit a rejected draft.
  const isCollabRejected =
    rowData.initiationType === "team" &&
    (rowData.statusKey === "Rejected" || rowData.statusKey === "Team Rejected");
  const approveVisible =
    permissionKeys.includes("can:sendExternalRecordToRo") &&
    actionsVisible &&
    !isCollabRejected;
  const approveVisibleforInternal =
    permissionKeys.includes("can:sendInternalRecordToRo") &&
    actionsVisible &&
    !isCollabRejected;
  // Secure / urgent toggles: visible when the user has permission AND either
  // the record is in an action-eligible status (so they can mark) OR the
  // record is already secured / urgent (so they can undo it from any status).
  const recordTypeKey = rowData?.recordTypeKey;
  const isDirectRecord = rowData.recordTypeKey
    ?.toLowerCase()
    .includes("direct");
  const isDirectOrInternalMemo =
    isDirectRecord || recordTypeKey === "internal_memo";

  const secureRecordVisible =
    permissionKeys.includes("can:createSecureRecord") &&
    (actionsVisible || rowData.isSecured) &&
    !isDirectOrInternalMemo;
  const urgentRecordVisible =
    permissionKeys.includes("can:createUrgentRecord") &&
    (actionsVisible || rowData.isUrgent);
  const sendInternal =
    permissionKeys.includes("can:sendInternalRecordToRo") &&
    actionsVisible &&
    !isCollabRejected;
  const sendInternalMemo =
    permissionKeys.includes("can:dispatchInternalMemo") &&
    actionsVisible &&
    !isCollabRejected;
  const sendExternal =
    permissionKeys.includes("can:sendExternalRecordToRo") &&
    actionsVisible &&
    !isCollabRejected;
  const canApprove =
    (sendExternal && recordTypeKey === "external") ||
    (sendInternal && recordTypeKey === "internal") ||
    (sendInternalMemo && recordTypeKey === "internal_memo");
  const sendVisible =
    isDirectRecord &&
    actionsVisible &&
    rowData.statusKey !== "Team Signature" &&
    rowData.statusKey !== "Team Rejected";
  const forceDispatchVisible =
    isDirectRecord &&
    (rowData.statusKey === "Team Signature" ||
      rowData.statusKey === "Team Rejected");
  const canBeDeleted = actionsVisible && rowData.statusKey === "Draft";

  const isCollaborationRecord = rowData.initiationType === "team";
  const activeContentId =
    rowData.content?.find((content) => content.isCurrent)?.id ??
    rowData.content?.[0]?.id;
  const canManageTeamCollaboration =
    isCollaborationRecord && isSelf && shouldShowAction;
  const canOpenTeamComments =
    canManageTeamCollaboration && Boolean(activeContentId);
  const forwardVisible =
    (checkHaveParent !== null || isCollaborationRecord) &&
    actionsVisible &&
    !isDirectRecord;
  // Allow the menu to open even on blocked statuses if the record is
  // currently secured or urgent — the creator still needs a way to undo
  // those flags after the record has moved past Draft/Adjustment.
  const canUndoSecureOrUrgent =
    Boolean(rowData.isSecured) || Boolean(rowData.isUrgent);
  const shouldShowMenu =
    !["Submitted", "Rejected", "Team Signature"].includes(rowData?.statusKey) ||
    canManageTeamCollaboration ||
    canUndoSecureOrUrgent ||
    forceDispatchVisible;
  const canDownload =
    rowData.statusKey === "Dispatched" || rowData.statusKey === "Approved";
  const canShareViaEmail = rowData.statusKey === "Dispatched";
  const hasInlineActions =
    shouldShowMenu &&
    isSelf &&
    ((shouldShowAction && actionsVisible) ||
      canDownload ||
      canManageTeamCollaboration ||
      (shouldShowAction && canUndoSecureOrUrgent) ||
      forceDispatchVisible);
  /** ✅ Secure and Urgent labels/icons */
  const isSecure = rowData.isSecured;
  const isUrgent = rowData.isUrgent;
  const secureLabel = isSecure
    ? t("userRecord.UnsecureRecord")
    : t("userRecord.MakeRecordSecure");
  const urgentLabel = isUrgent
    ? t("userRecord.UnmarkUrgent")
    : t("userRecord.MarkUrgent");
  const SecureIcon = isSecure ? Unlock : Key;
  const UrgentIcon = AlertTriangle;
  // Edit is hidden for both "Rejected" and "Team Rejected" — the creator
  // cannot revise a rejected record from the Outgoing tab.
  const canEdit =
    shouldShowAction &&
    isSelf &&
    (rowData.statusKey === "Draft" ||
      rowData.statusKey === "Adjustment" ||
      rowData.statusKey === "Team Adjusted" ||
      rowData.statusKey === "Team Rejected" ||
      rowData.statusKey === "Returned" ||
      (isCollaborationRecord &&
        allowEditOnCollaboration &&
        rowData.statusKey === "Team Signature"));

  return (
    <>
      {" "}
      {fromTable ? (
        <div className="flex">
          <Button variant={"viewDetail"} onClick={handleViewDetails}>
            {t("userRecord.View Detail")}
          </Button>

          {shouldShowMenu && isSelf && (
            <DropdownMenu open={isDropdownOpen} onOpenChange={onDropdownOpenChange || (() => {})}>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
                  aria-haspopup="menu"
                  aria-expanded={isDropdownOpen}
                >
                  <EllipsisVertical className="h-4 w-4" />
                  <span className="sr-only">
                    {t("userRecord.Open actions menu")}
                  </span>
                </Button>
              </DropdownMenuTrigger>

              <DropdownMenuContent
                align="end"
                className="w-[200px]"
                onCloseAutoFocus={(e) => e.preventDefault()}
                onInteractOutside={(e) => {
                  const target = e.target as HTMLElement;
                  if (target.closest('[role="dialog"]')) e.preventDefault();
                }}
              >
                {shouldShowAction && actionsVisible && (
                  <>
                    {canApprove && (
                      <DropdownMenuItem
                        onSelect={
                          allCollaboratorsCompleted
                            ? handleApproveClick
                            : (e) => {
                                e.preventDefault();
                                toast.error(
                                  t(
                                    "userRecord.waitingForCollaborators",
                                    "Cannot approve: Waiting for all collaborators to complete their actions",
                                  ),
                                );
                              }
                        }
                        disabled={!allCollaboratorsCompleted}
                        className={`cursor-pointer !bg-transparent ${
                          !allCollaboratorsCompleted
                            ? "opacity-50 cursor-not-allowed hover:!text-primary-700"
                            : "hover:!text-primary-700"
                        }`}
                      >
                        <SquareCheckBig className="mr-2 h-4 w-4" />
                        {t("userRecord.Approve")}
                        {!allCollaboratorsCompleted && (
                          <span className="ml-2 text-xs text-orange-600">
                            (Waiting)
                          </span>
                        )}
                      </DropdownMenuItem>
                    )}

                    {forwardVisible && (
                      <DropdownMenuItem
                        onSelect={
                          allCollaboratorsCompleted
                            ? handleForwardClick
                            : (e) => {
                                e.preventDefault();
                                toast.error(
                                  t(
                                    "userRecord.waitingForCollaborators",
                                    "Cannot forward: Waiting for all collaborators to complete their actions",
                                  ),
                                );
                              }
                        }
                        disabled={!allCollaboratorsCompleted}
                        className={`cursor-pointer !bg-transparent ${
                          !allCollaboratorsCompleted
                            ? "opacity-50 cursor-not-allowed hover:!text-primary-700"
                            : "hover:!text-primary-700"
                        }`}
                      >
                        <ForwardIcon className="mr-2 h-4 w-4" />
                        {t("userRecord.Forward")}
                        {!allCollaboratorsCompleted && (
                          <span className="ml-2 text-xs text-orange-600">
                            (Waiting)
                          </span>
                        )}
                      </DropdownMenuItem>
                    )}

                    {canEdit && (
                      <DropdownMenuItem
                        onSelect={handleEditClick}
                        className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                      >
                        <SquarePen className="mr-2 h-4 w-4" />
                        {t("userRecord.Edit")}
                      </DropdownMenuItem>
                    )}

                    {secureRecordVisible && (
                      <DropdownMenuItem
                        onSelect={(e) => {
                          e.preventDefault();
                          setIsOpenSecure(true);
                        }}
                        className={`cursor-pointer !bg-transparent ${
                          isSecure
                            ? "text-yellow-600 hover:!text-yellow-800"
                            : "text-red-600 hover:!text-red-800"
                        }`}
                      >
                        <SecureIcon className="mr-2 h-4 w-4" />
                        {secureLabel}
                      </DropdownMenuItem>
                    )}

                    {urgentRecordVisible && (
                      <DropdownMenuItem
                        onSelect={(e) => {
                          e.preventDefault();
                          setIsOpenUrgent(true);
                        }}
                        className={`cursor-pointer !bg-transparent ${
                          isUrgent
                            ? "text-orange-600 hover:!text-orange-800"
                            : "text-primary-600 hover:!text-primary-800"
                        }`}
                      >
                        <UrgentIcon className="mr-2 h-4 w-4" />
                        {urgentLabel}
                      </DropdownMenuItem>
                    )}

                    {sendVisible && (
                      <DropdownMenuItem
                        onSelect={(e) => {
                          e.preventDefault();
                          handleSendClick();
                        }}
                        className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                      >
                        <Mail className="mr-2 h-4 w-4" />
                        {t("userRecord.Send")}
                      </DropdownMenuItem>
                    )}

                    {forceDispatchVisible && (
                      <DropdownMenuItem
                        onSelect={(e) => {
                          e.preventDefault();
                          handleForceDispatchClick();
                        }}
                        className="cursor-pointer hover:!text-primary !bg-transparent"
                      >
                        <Send className="mr-2 h-4 w-4" />
                        {t("userRecord.SendDirectly", "Send Directly")}
                      </DropdownMenuItem>
                    )}

                    {canBeDeleted && (
                      <DropdownMenuItem
                        onSelect={handleDeleteClick}
                        className="text-red-600 cursor-pointer hover:!text-red-800 !bg-transparent"
                      >
                        <Trash2 className="mr-2 h-4 w-4 text-red-600" />
                        {t("userRecord.Delete")}
                      </DropdownMenuItem>
                    )}
                  </>
                )}

                {canDownload && (
                  <DropdownMenuItem
                    onSelect={handleDownloadClick}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                  >
                    <Download className="mr-2 h-4 w-4" />
                    {t("userRecord.Download")}
                  </DropdownMenuItem>
                )}

                {canOpenTeamComments && (
                  <DropdownMenuItem
                    onSelect={handleCollaborationCommentsClick}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                  >
                    <MessageSquareText className="mr-2 h-4 w-4" />
                    {t("collaboration.comments", "Comments")}
                  </DropdownMenuItem>
                )}

                {canManageTeamCollaboration && (
                  <DropdownMenuItem
                    onSelect={handleCollaborationDetailsClick}
                    className="cursor-pointer hover:!text-primary-700 !bg-transparent"
                  >
                    <Users className="mr-2 h-4 w-4" />
                    {t("header.navigation.collaboration")}
                  </DropdownMenuItem>
                )}

                {/* {canShareViaEmail && (
              <DropdownMenuItem
                onSelect={handleShareEmailClick}
                className="cursor-pointer hover:!text-primary-700 !bg-transparent"
              >
                <Mail className="mr-2 h-4 w-4" />
                {t("userRecord.ShareViaEmail")}
              </DropdownMenuItem>
            )} */}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
          {(rowData?.statusKey === "Dispatched" ||
            (rowData?.recordTypeKey === "internal_memo" &&
              rowData?.statusKey === "Approved")) && (
            <IncomingInstanceDetail
              instanceId={rowData?.id as string}
              instanceType={"outgoing"}
              rowData={rowData}
            />
          )}
        </div>
      ) : (
        <>
          {hasInlineActions ? (
            <div className="flex flex-wrap gap-2">
              {shouldShowAction && actionsVisible && (
                <>
                  {(approveVisible ||
                    approveVisibleforInternal ||
                    (sendExternal && rowData?.recordTypeKey === "external") ||
                    (sendInternal && rowData?.recordTypeKey === "internal") ||
                    (sendInternalMemo &&
                      rowData?.recordTypeKey === "internal_memo")) && (
                    <Button
                      variant={getActionButtonVariant("Approve")}
                      onClick={
                        allCollaboratorsCompleted
                          ? handleApproveClick
                          : (e) => {
                              e.preventDefault();
                              toast.error(
                                t(
                                  "userRecord.waitingForCollaborators",
                                  "Cannot approve: Waiting for all collaborators to complete their actions",
                                ),
                              );
                            }
                      }
                      disabled={!allCollaboratorsCompleted}
                      className={`h-9 px-4 flex items-center gap-2 rounded-full shadow-sm hover:shadow-md transition-all duration-300 ${
                        allCollaboratorsCompleted
                          ? "bg-gradient-to-r from-emerald-50 to-green-50 border-emerald-200 hover:from-emerald-100 hover:to-green-100 hover:border-emerald-300 hover:text-emerald-700"
                          : "opacity-50 cursor-not-allowed bg-gray-100 border-gray-200"
                      }`}
                    >
                      <SquareCheckBig
                        className={`h-4 w-4 ${
                          allCollaboratorsCompleted
                            ? "text-emerald-600"
                            : "text-gray-400"
                        }`}
                      />
                      <span
                        className={`text-sm font-medium ${
                          allCollaboratorsCompleted
                            ? "text-emerald-700"
                            : "text-gray-600"
                        }`}
                      >
                        {t("userRecord.Approve")}
                        {!allCollaboratorsCompleted && " (Waiting)"}
                      </span>
                    </Button>
                  )}
                  {forwardVisible && (
                    <Button
                      variant={getActionButtonVariant("Forward")}
                      onClick={
                        allCollaboratorsCompleted
                          ? handleForwardClick
                          : (e) => {
                              e.preventDefault();
                              toast.error(
                                t(
                                  "userRecord.waitingForCollaborators",
                                  "Cannot forward: Waiting for all collaborators to complete their actions",
                                ),
                              );
                            }
                      }
                      disabled={!allCollaboratorsCompleted}
                    >
                      <ForwardIcon className="h-4 w-4" />
                      <span>{t("userRecord.Forward")}</span>
                    </Button>
                  )}

                  {sendVisible && (
                    <Button
                      variant={getActionButtonVariant("Send")}
                      onClick={handleSendClick}
                    >
                      <Mail className="h-4 w-4" />
                      <span>{t("userRecord.Send")}</span>
                    </Button>
                  )}

                  {forceDispatchVisible && (
                    <Button
                      variant={getActionButtonVariant("Send Directly")}
                      onClick={handleForceDispatchClick}
                    >
                      <Send className="h-4 w-4" />
                      <span>
                        {t("userRecord.SendDirectly", "Send Directly")}
                      </span>
                    </Button>
                  )}

                  {canEdit && (
                    <Button
                      variant={getActionButtonVariant("Edit")}
                      onClick={handleEditClick}
                    >
                      <SquarePen className="h-4 w-4" />
                      <span>{t("userRecord.Edit")}</span>
                    </Button>
                  )}

                  {secureRecordVisible && (
                    <Button
                      variant={getActionButtonVariant("Secure Letter")}
                      onClick={(e) => {
                        e.preventDefault();
                        setIsOpenSecure(true);
                      }}
                    >
                      <SecureIcon className="h-4 w-4" />
                      <span>{secureLabel}</span>
                    </Button>
                  )}

                  {urgentRecordVisible && (
                    <Button
                      variant={getActionButtonVariant("Make Urgent")}
                      onClick={(e) => {
                        e.preventDefault();
                        setIsOpenUrgent(true);
                      }}
                    >
                      <UrgentIcon className="h-4 w-4" />
                      <span>{urgentLabel}</span>
                    </Button>
                  )}

                  {canBeDeleted && (
                    <Button
                      variant={getActionButtonVariant("Delete")}
                      onClick={handleDeleteClick}
                    >
                      <Trash2 className="h-4 w-4" />
                      <span>{t("userRecord.Delete")}</span>
                    </Button>
                  )}
                </>
              )}

              {/* Unsecure / Unmark Urgent — available on any status when the
                  record is already flagged, so the creator can still undo it
                  after the record has moved past Draft/Adjustment. */}
              {shouldShowAction &&
                !actionsVisible &&
                isSecure &&
                !isDirectOrInternalMemo &&
                permissionKeys.includes("can:createSecureRecord") && (
                  <Button
                    variant={getActionButtonVariant("Secure Letter")}
                    onClick={(e) => {
                      e.preventDefault();
                      setIsOpenSecure(true);
                    }}
                  >
                    <SecureIcon className="h-4 w-4" />
                    <span>{secureLabel}</span>
                  </Button>
                )}

              {shouldShowAction &&
                !actionsVisible &&
                isUrgent &&
                permissionKeys.includes("can:createUrgentRecord") && (
                  <Button
                    variant={getActionButtonVariant("Make Urgent")}
                    onClick={(e) => {
                      e.preventDefault();
                      setIsOpenUrgent(true);
                    }}
                  >
                    <UrgentIcon className="h-4 w-4" />
                    <span>{urgentLabel}</span>
                  </Button>
                )}

              {canDownload && (
                <Button
                  variant={getActionButtonVariant("Download")}
                  onClick={handleDownloadClick}
                >
                  <Download className="h-4 w-4" />
                  <span>{t("userRecord.Download")}</span>
                </Button>
              )}

              {canOpenTeamComments && (
                <Button
                  variant={getActionButtonVariant("Comment")}
                  onClick={handleCollaborationCommentsClick}
                >
                  <MessageSquareText className="h-4 w-4" />
                  <span>{t("collaboration.comments", "Comments")}</span>
                </Button>
              )}

              {canManageTeamCollaboration && (
                <Button
                  variant={getActionButtonVariant("Collaboration")}
                  onClick={handleCollaborationDetailsClick}
                >
                  <Users className="h-4 w-4" />
                  <span>{t("header.navigation.collaboration")}</span>
                </Button>
              )}
              {(rowData?.statusKey === "Dispatched" ||
                (rowData?.recordTypeKey === "internal_memo" &&
                  rowData?.statusKey === "Approved")) && (
                <IncomingInstanceDetail
                  instanceId={rowData?.id as string}
                  instanceType={"outgoing"}
                  rowData={rowData}
                  fromTable={false}
                />
              )}
              {/* {canShareViaEmail && (
      <Button
        variant="outline"
        size="sm"
        onClick={handleShareEmailClick}
        className="h-9 px-4 flex items-center gap-2 rounded-full bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200 hover:from-slate-100 hover:to-gray-100 hover:border-slate-300 hover:text-slate-700 transition-all duration-300 shadow-sm hover:shadow-md"
      >
        <Mail className="h-4 w-4 text-slate-600" />
        <span className="text-sm font-medium text-slate-700">
          {t("userRecord.ShareViaEmail")}
        </span>
      </Button>
    )} */}
            </div>
          ) : (
            <p className="text-sm text-gray-500 dark:text-gray-400 italic">
              {t("userIncoming.noActionsAvailable", {
                defaultValue: "No actions available for this record.",
              })}
            </p>
          )}
        </>
      )}
      {/* --- Modals --- */}
      {showDeleteDialog && (
        <DeleteRecord
          recordId={rowData?.id || "0"}
          onSuccess={() => {
            setShowDeleteDialog(false);
            if (fromTable) {
              if (refetchTable) refetchTable();
            } else {
              navigate(getOutgoingListUrl(), { replace: true });
            }
          }}
          onClose={() => setShowDeleteDialog(false)}
        />
      )}
      {showDownloadDialog && (
        <DownloadRecord
          recordId={rowData?.id || "0"}
          onSuccess={() => setShowDownloadDialog(false)}
          onClose={() => {
            setShowDownloadDialog(false);
            if (refetchTable) refetchTable();
          }}
        />
      )}
      {showForward && (
        <ForwardRecord
          recordId={rowData?.id}
          onSuccess={() => {
            setShowForward(false);
            if (refetchTable) refetchTable();
          }}
          onClose={() => setShowForward(false)}
        />
      )}
      {showApprove && (
        <ApproveRecord
          recordId={rowData?.id}
          recordData={{
            unitId: rowData?.unitId,
            recordTypeKey: rowData?.recordTypeKey,
          }}
          onSuccess={() => {
            setShowApprove(false);
            if (fromTable) {
              if (refetchTable) refetchTable();
            } else {
              // On the detail page, send the user back to the outgoing
              // records table after a successful approve.
              navigate("/record-management/userRecords");
            }
          }}
          onClose={() => setShowApprove(false)}
          open={showApprove}
          preferredLanguage={rowData?.preferredLanguage}
        />
      )}
      {showShareEmail && (
        <ShareViaEmail
          recordId={rowData?.id || "0"}
          open={showShareEmail}
          onSuccess={() => {
            setShowShareEmail(false);
            if (refetchTable) refetchTable();
          }}
          onClose={() => setShowShareEmail(false)}
        />
      )}
      {showCollaborationComments && activeContentId && (
        <CollaborationCommentsDialog
          open={showCollaborationComments}
          onClose={() => setShowCollaborationComments(false)}
          recordId={rowData.id}
          contentId={activeContentId}
          recordStatus={rowData.statusKey}
        />
      )}
      {showCollaborationDetails && (
        <TeamRecordCollaborationDetailsDialog
          open={showCollaborationDetails}
          onClose={() => setShowCollaborationDetails(false)}
          recordId={rowData.id}
        />
      )}
      {/* ✅ Secure / Unsecure Confirm Dialog */}
      <AlertDialog
        open={showForceDispatchDialog}
        onOpenChange={setShowForceDispatchDialog}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("userRecord.SendDirectly", "Send Directly")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "userRecord.forceDispatchDescription",
                "This will force dispatch the direct team record.",
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isForceDispatchingCollaborator}>
              {t("common.Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={async (event) => {
                event.preventDefault();
                try {
                  await forceDispatchCollaborator({
                    recordId: rowData.id,
                    type: isDirectRecord ? "direct" : "other",
                  });
                  setShowForceDispatchDialog(false);
                  if (refetchTable) refetchTable();
                } catch (error) {
                  console.error(error);
                }
              }}
              disabled={isForceDispatchingCollaborator}
            >
              {isForceDispatchingCollaborator
                ? t("userRecord.Sending", "Sending...")
                : t("userRecord.SendDirectly", "Send Directly")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <AlertDialog open={isOpenSecure} onOpenChange={setIsOpenSecure}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {isSecure
                ? t("userRecord.UnsecureDialogTitle")
                : t("userRecord.SecureDialogTitle")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {isSecure
                ? t("userRecord.UnsecureDialogDescription")
                : t("userRecord.SecureDialogDescription")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.Cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleSecureConfirm}>
              {t("common.Confirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      {/* ✅ Urgent / Unmark Urgent Confirm Dialog */}
      <AlertDialog open={isOpenUrgent} onOpenChange={setIsOpenUrgent}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {isUrgent
                ? t("userRecord.UnmarkUrgentDialogTitle")
                : t("userRecord.MarkUrgentDialogTitle")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {isUrgent
                ? t("userRecord.UnmarkUrgentDialogDescription")
                : t("userRecord.MarkUrgentDialogDescription")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.Cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleUrgentConfirm}>
              {t("common.Confirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      {/* ✅ Send Direct Record Confirm Dialog */}
      {showSend && (
        <SendRecord
          recordId={rowData?.id || "0"}
          onSuccess={() => {
            setShowSend(false);
            if (refetchTable) refetchTable();
          }}
          onClose={() => setShowSend(false)}
        />
      )}
    </>
  );
};

export default UserRecordsActions;
