for status === pending and when projectlead === true, do not show DropdownVertical icon. "import React, { useState, useRef, useCallback, useMemo } from "react";
import { useClickAway } from "react-use";
import { useSelector } from "react-redux";
import toast from "react-hot-toast";

import "../../transactionManageDesktop/transactionListDesktop.css";
import { archiveTransaction, TransactionProps } from "../helper";
import getStatusButton from "@/scenes/transactionManageDesktop/getStatusButton";
import {
  handleUndoTransaction,
  handleRejectTransaction,
  handleApproveTransaction,
} from "@/scenes/transactionManage/helper";
import RejectionNoteModal from "@/scenes/transactionManageDesktop/RejectionNoteModal";
import ConfirmDelete from "@/scenes/transactionManageDesktop/ConfirmDelete";
import EditTransactionModal from "../editTransactionModal";
import { RootState } from "@/redux/store";

// Icons
import TransactionManageGreenButton from "@/components/Icons/SVG/Transaction_Manage_green_button.svg";
import TransactionManageRedButton from "@/components/Icons/SVG/Transaction_Manage_red_button.svg";
import DropDownVertical from "@/components/Icons/SVG/Dropdown.svg";

type ReviewMenuProps = {
  tx: TransactionProps;
  index: number;
  isProjectLead: boolean;
  isProjectReporter: boolean;
  token: string | null;
  tsxList: TransactionProps[];
  setTsxList: React.Dispatch<React.SetStateAction<TransactionProps[]>>;
};

type DropdownItem = {
  label: string;
  onClick: () => void;
};

type ModalState = {
  rejection: boolean;
  edit: boolean;
  delete: boolean;
};

const ReviewMenu: React.FC<ReviewMenuProps> = ({
  tx,
  index,
  isProjectLead,
  isProjectReporter,
  token,
  tsxList,
  setTsxList,
}) => {
  // State management
  const [modals, setModals] = useState<ModalState>({
    rejection: false,
    edit: false,
    delete: false,
  });
  const [dropdown, setDropdown] = useState({
    isOpen: false,
    selectedTx: null as TransactionProps | null,
  });
  const [editingTransaction, setEditingTransaction] = useState<{
    transaction: TransactionProps | null;
    index: number;
  }>({ transaction: null, index: -1 });

  // Redux state
  const { firstname, lastname } = useSelector((state: RootState) => state.auth);

  // Refs
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useClickAway(dropdownRef, () => {
    setDropdown({ isOpen: false, selectedTx: null });
  });

  // Computed values
  const currentFullName = useMemo(
    () => `${firstname ?? ""} ${lastname ?? ""}`.trim().toLowerCase(),
    [firstname, lastname],
  );

  const txFullName = useMemo(
    () => (tx.user ?? "").trim().toLowerCase(),
    [tx.user],
  );

  const isTransactionOwner = useMemo(
    () => currentFullName === txFullName,
    [currentFullName, txFullName],
  );

  // Modal handlers
  const openModal = useCallback((modalType: keyof ModalState) => {
    setModals((prev) => ({ ...prev, [modalType]: true }));
    setDropdown({ isOpen: false, selectedTx: null });
  }, []);

  const closeModal = useCallback((modalType: keyof ModalState) => {
    setModals((prev) => ({ ...prev, [modalType]: false }));
    if (modalType === "edit") {
      setEditingTransaction({ transaction: null, index: -1 });
    }
  }, []);

  const closeAllModals = useCallback(() => {
    setModals({ rejection: false, edit: false, delete: false });
    setEditingTransaction({ transaction: null, index: -1 });
  }, []);

  // Transaction actions
  const handleApprove = useCallback(async () => {
    if (!token) {
      toast.error("Authentication error occurred", { duration: 3000 });
      return;
    }

    try {
      await handleApproveTransaction(Number(tx.id), token);

      setTsxList((prevList) =>
        prevList.map((transaction, idx) =>
          idx === index
            ? {
                ...transaction,
                reviewer: {
                  firstName: firstname ?? "",
                  lastName: lastname ?? "",
                },
                status: "Accepted",
              }
            : transaction,
        ),
      );

      setDropdown({ isOpen: false, selectedTx: null });
      toast.success("Transaction approved successfully!", { duration: 2000 });
    } catch (error) {
      console.error("Error approving transaction:", error);
      toast.error("Failed to approve transaction. Please try again.", {
        duration: 3000,
      });
    }
  }, [token, tx.id, index, firstname, lastname, setTsxList]);

  const handleReject = useCallback(() => {
    setTsxList((prevList) =>
      prevList.map((transaction) =>
        transaction.id === Number(tx.id)
          ? { ...transaction, reviewerNote: "" }
          : transaction,
      ),
    );
    openModal("rejection");
  }, [tx.id, setTsxList, openModal]);

  const handleUndo = useCallback(async () => {
    if (!token) {
      toast.error("Authentication error occurred", { duration: 3000 });
      return;
    }

    try {
      await handleUndoTransaction(Number(tx.id), token);

      setTsxList((prevList) =>
        prevList.map((transaction) =>
          transaction.id === tx.id
            ? {
                ...transaction,
                reviewer: { firstName: "", lastName: "" },
                reviewerNote: "",
                status: "Pending",
              }
            : transaction,
        ),
      );

      closeAllModals();
      toast.success("Transaction undone successfully!", { duration: 2000 });
    } catch (error) {
      console.error("Error undoing transaction:", error);
      toast.error("Failed to undo transaction. Please try again.", {
        duration: 2000,
      });
    }
  }, [token, tx.id, setTsxList, closeAllModals]);

  const handleEdit = useCallback(() => {
    setEditingTransaction({ transaction: tx, index });
    openModal("edit");
  }, [tx, index, openModal]);

  const handleArchive = useCallback(async () => {
    if (!token) {
      toast.error("Authentication error occurred", { duration: 3000 });
      return;
    }

    try {
      const success = await archiveTransaction(
        Number(tx.id),
        token,
        setTsxList,
      );
      if (success) {
        closeAllModals();
        toast.success("Transaction archived successfully!", { duration: 2000 });
      } else {
        toast.error("Failed to archive transaction", { duration: 3000 });
      }
    } catch (error) {
      console.error("Error archiving transaction:", error);
      toast.error("An error occurred while archiving transaction", {
        duration: 3000,
      });
    }
  }, [token, tx.id, setTsxList, closeAllModals]);

  const handleRejectSubmit = useCallback(
    async (id: number, note: string, txIndex: number) => {
      if (!token) {
        toast.error("Authentication error occurred", { duration: 3000 });
        return;
      }

      try {
        await handleRejectTransaction(id, note, token);

        setTsxList((prevList) =>
          prevList.map((transaction, idx) =>
            idx === txIndex
              ? {
                  ...transaction,
                  reviewer: {
                    firstName: firstname ?? "",
                    lastName: lastname ?? "",
                  },
                  reviewerNote: note,
                  status: "Rejected",
                }
              : transaction,
          ),
        );

        closeAllModals();
        toast.success("Transaction rejected successfully!", { duration: 2000 });
      } catch (error) {
        console.error("Error rejecting transaction:", error);
        toast.error("Failed to reject transaction. Please try again.", {
          duration: 2000,
        });
      }
    },
    [token, firstname, lastname, setTsxList, closeAllModals],
  );

  // Dropdown handlers
  const toggleDropdown = useCallback(() => {
    setDropdown((prev) => ({
      isOpen: !prev.isOpen,
      selectedTx: prev.selectedTx?.id === tx.id ? null : tx,
    }));
  }, [tx]);

  const handleViewRejection = useCallback(() => {
    openModal("rejection");
  }, [openModal]);

  // Dropdown items configuration
  const getDropdownItems = useCallback((): DropdownItem[] => {
    switch (tx.status) {
      case "Pending":
        return [
          { label: "Edit", onClick: handleEdit },
          { label: "Archive", onClick: () => openModal("delete") },
        ];
      case "Accepted":
        return [{ label: "Undo", onClick: handleUndo }];
      case "Rejected":
        // For regular users (non-reporters, non-leads), only show "View" option
        if (!isProjectReporter && !isProjectLead) {
          return [{ label: "View", onClick: handleViewRejection }];
        }
        // For reporters and leads, show both options
        return [
          { label: "Undo", onClick: handleUndo },
          { label: "View", onClick: handleViewRejection },
        ];
      default:
        return [];
    }
  }, [
    tx.status,
    handleEdit,
    handleUndo,
    handleViewRejection,
    openModal,
    isProjectReporter,
    isProjectLead,
  ]);

  // Access control logic
  const canShowDropdown = useMemo(() => {
    // For rejected transactions, allow dropdown if user needs to view rejection note
    if (tx.status === "Rejected") {
      return true; // Everyone can see dropdown for rejected transactions to view rejection note
    }

    if (!isProjectReporter && !isProjectLead) {
      return false; // No access if neither reporter nor lead
    }

    return true;
  }, [tx.status, isProjectReporter, isProjectLead]);

  const canEditTransaction = useMemo(() => {
    return isProjectReporter || (isProjectLead && isTransactionOwner);
  }, [isProjectReporter, isProjectLead, isTransactionOwner]);

  const canApproveReject = useMemo(() => {
    return isProjectLead;
  }, [isProjectLead]);

  // CSS classes
  const dropdownItemClass =
    "cursor-pointer text-center text-xs text-[#171717] dark:text-[#b4b5b8] hover:underline hover:dark:hover:text-white hover:underline-offset-4";

  // Don't render anything for inactive transactions
  if (!tx?.isTransactionActive) {
    return (
      <div className="review-menu">
        {getStatusButton({ status: undefined })}
      </div>
    );
  }

  // Pending status rendering
  if (tx.status === "Pending") {
    return (
      <div
        ref={dropdownRef}
        className="review-menu relative flex items-center gap-4"
      >
        {/* Approve/Reject buttons - only for project leads */}
        {canApproveReject && (
          <>
            <button
              className="approve-button"
              onClick={handleApprove}
              aria-label="Approve transaction"
            >
              <img
                src={TransactionManageGreenButton}
                alt="Approve"
                className="action-icon"
              />
            </button>
            <button
              className="reject-button"
              onClick={handleReject}
              aria-label="Reject transaction"
            >
              <img
                src={TransactionManageRedButton}
                alt="Reject"
                className="action-icon"
              />
            </button>
          </>
        )}

        {/* Status button for non-leads */}
        {!canApproveReject && getStatusButton({ status: null })}

        {/* Dropdown menu */}
        {canShowDropdown && (
          <>
            <div
              className="dropdown-button ml-2 cursor-pointer"
              onClick={toggleDropdown}
            >
              <img
                src={DropDownVertical}
                alt="More options"
                className="dropdown-icon"
              />
            </div>

            {dropdown.isOpen && dropdown.selectedTx?.id === tx.id && (
              <ul className="absolute right-0 top-[2.5rem] z-20 flex w-[6rem] flex-col gap-2 rounded-xl bg-[#fcf3ea] py-2 shadow-md dark:bg-[#333746]">
                {getDropdownItems()
                  .filter((item) => item.label !== "Edit" || canEditTransaction)
                  .map((item, idx) => (
                    <li
                      key={idx}
                      className={dropdownItemClass}
                      onClick={item.onClick}
                    >
                      {item.label}
                    </li>
                  ))}
              </ul>
            )}
          </>
        )}

        {/* Modals */}
        {modals.edit && editingTransaction.transaction && (
          <EditTransactionModal
            isOpen={modals.edit}
            onClose={() => closeModal("edit")}
            transaction={editingTransaction.transaction}
            token={token}
            index={editingTransaction.index}
            setTsxList={setTsxList}
          />
        )}

        {modals.delete && (
          <ConfirmDelete
            open={modals.delete}
            onClose={() => closeModal("delete")}
            onConfirm={handleArchive}
            resourceName="Transaction"
          />
        )}

        {modals.rejection && (
          <RejectionNoteModal
            open={modals.rejection}
            onClose={() => closeModal("rejection")}
            onSubmit={handleRejectSubmit}
            id={Number(tx.id)}
            index={index}
            // transactionReviewerNote={tx.reviewerNote || ""}
            transactionReviewerNote={tsxList[index].reviewerNote || ""} 
          />
        )}
      </div>
    );
  }

  // Accepted status rendering
  if (tx.status === "Accepted") {
    return (
      <div className="review-menu-container">
        <div ref={dropdownRef} className="review-menu relative">
          {getStatusButton({ status: true })}

          {canShowDropdown && isProjectLead && (
            <>
              <div className="dropdown-button" onClick={toggleDropdown}>
                <img
                  src={DropDownVertical}
                  alt="More options"
                  className="dropdown-icon"
                />
              </div>

              {dropdown.isOpen && dropdown.selectedTx?.id === tx.id && (
                <ul className="absolute right-2 top-[2rem] z-20 flex w-[6rem] flex-col gap-4 rounded-xl bg-[#fcf3ea] py-3 shadow-md dark:bg-[#333746]">
                  {getDropdownItems().map((item, idx) => (
                    <li
                      key={idx}
                      className={dropdownItemClass}
                      onClick={item.onClick}
                    >
                      {item.label}
                    </li>
                  ))}
                </ul>
              )}
            </>
          )}
        </div>

        {tx.reviewer && (
          <p className="mt-1 text-xs text-[#171717] dark:text-[#A4A6AD]">
            Reviewed by{" "}
            {firstname === tx.reviewer.firstName &&
            lastname === tx.reviewer.lastName
              ? "you"
              : `${tx.reviewer.firstName} ${tx.reviewer.lastName}`}
          </p>
        )}
      </div>
    );
  }

  // Rejected status rendering
  if (tx.status === "Rejected") {
    return (
      <div className="review-menu-container">
        <div ref={dropdownRef} className="review-menu relative">
          {getStatusButton({ status: false })}

          {canShowDropdown && (
            <>
              <div className="dropdown-button" onClick={toggleDropdown}>
                <img
                  src={DropDownVertical}
                  alt="More options"
                  className="dropdown-icon"
                />
              </div>

              {dropdown.isOpen && dropdown.selectedTx?.id === tx.id && (
                <ul className="absolute right-2 top-[2rem] z-20 flex w-[6rem] flex-col gap-4 rounded-xl bg-[#fcf3ea] py-4 shadow-md dark:bg-[#333746]">
                  {getDropdownItems().map((item, idx) => (
                    <li
                      key={idx}
                      className={dropdownItemClass}
                      onClick={item.onClick}
                    >
                      {item.label}
                    </li>
                  ))}
                </ul>
              )}
            </>
          )}
        </div>

        {tx.reviewer && (
          <p className="mt-1 text-xs text-[#171717] dark:text-[#A4A6AD]">
            Rejected by{" "}
            {firstname === tx.reviewer.firstName &&
            lastname === tx.reviewer.lastName
              ? "you"
              : `${tx.reviewer.firstName} ${tx.reviewer.lastName}`}
          </p>
        )}

        {/* Rejection modal - available for all users */}
        {modals.rejection && (
          <RejectionNoteModal
            open={modals.rejection}
            onClose={() => closeModal("rejection")}
            onSubmit={
              isProjectReporter || isProjectLead
                ? handleRejectSubmit
                : undefined
            }
            id={Number(tx.id)}
            index={index}
            transactionReviewerNote={tx.reviewerNote || ""}
            readOnly={!isProjectReporter && !isProjectLead}
          />
        )}
      </div>
    );
  }

  return null;
};

export default ReviewMenu;"