import { IconEdit, IconEye, IconUserShare } from '@material-hu/icons/tabler';

import HuMenuList from '@material-hu/components/composed-components/MenuList';
import { type MenuListProps } from '@material-hu/components/composed-components/MenuList/types';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetManagerTypes } from 'src/hooks/queryHooks/vacations';
import { type BalanceReport } from 'src/types/vacations';
import { insertIf } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { isBasicAllowance } from 'src/utils/vacations';

import { type CreateRequestDrawerProps } from '../Drawers/CreateRequestDrawer';

export type ReportBalanceMenuProps = {
  onOpenAdjustAvailableTime: () => void;
  showRequestByManagerDrawer: (
    props: Partial<CreateRequestDrawerProps>,
  ) => void;
  reportItem: BalanceReport;
  showPolicyBalanceDetailDrawer: (
    props: Partial<CreateRequestDrawerProps>,
  ) => void;
};

export const ReportBalanceMenu = (props: ReportBalanceMenuProps) => {
  const {
    onOpenAdjustAvailableTime,
    showRequestByManagerDrawer,
    showPolicyBalanceDetailDrawer,
    reportItem,
  } = props;

  const { t } = useLokaliseTranslation('time_off');
  const { isAdmin } = useGetManagerTypes();
  const { user: currentUser } = useAuth();
  const allowedToRequestOnBehalfOf = currentUser?.id !== reportItem.user.id;

  const onHandleRequestByManager = () => {
    showRequestByManagerDrawer({
      policyTypes: [reportItem.policy?.policyType],
      user: reportItem.user,
      isManagerRequesting: true,
      policyTypeSelected: {
        value: reportItem.policy?.policyType?.id,
        label: reportItem.policy?.policyType?.name,
      },
    });
  };

  const onHandlePolicyBalanceDetail = () => {
    showPolicyBalanceDetailDrawer({});
  };

  const menuOptions: MenuListProps['options'] = [
    {
      title: t('see_detail'),
      onClick: onHandlePolicyBalanceDetail,
      Icon: IconEye,
    },
    ...insertIf(allowedToRequestOnBehalfOf, {
      title: t('request_on_behalf_of'),
      onClick: onHandleRequestByManager,
      Icon: IconUserShare,
    }),
    ...insertIf(isAdmin, {
      title: isBasicAllowance(reportItem.policy?.allowanceType!)
        ? t('adjust_available_time')
        : t('adjust_used_time'),
      onClick: onOpenAdjustAvailableTime,
      Icon: IconEdit,
    }),
  ];

  return <HuMenuList options={menuOptions} />;
};

export default ReportBalanceMenu;
