import {
  type GetDrawerConfiguration,
  useDrawerV2,
} from '@material-hu/hooks/useDrawerV2';
import { IconArrowRight } from '@material-hu/icons/tabler';
import CardActions from '@material-hu/mui/CardActions';
import CardContent from '@material-hu/mui/CardContent';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTitle from '@material-hu/components/design-system/Title';

import { useAuth } from 'src/contexts/JWTContext';
import { usePolicyTypeDetail } from 'src/hooks/queryHooks/vacations';
import { type User } from 'src/types/user';
import {
  AllowanceType,
  type PolicyTypes,
  UnitVacations,
} from 'src/types/vacations';
import { formatDateInVacations } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { getBalanceConformationDrawer } from './BalanceConformationDrawer';
import { useCreateRequestDrawer } from './CreateRequestDrawer';
import { getPolicyDescriptionDrawer } from './PolicyDescriptionDrawer';

export type PolicyBalanceDetailDrawer = {
  userCollaborator?: User;
  policyType: PolicyTypes;
};
export const getPolicyBalanceDetailDrawer: GetDrawerConfiguration<
  PolicyBalanceDetailDrawer
> = ({
  closeDrawer: closePolicyTypeDrawer,
  userCollaborator,
  open,
  policyType,
}) => {
  const { user } = useAuth();

  const { t } = useLokaliseTranslation('time_off');
  const isCollaboratorView = !userCollaborator;

  const { detail, isLoading } = usePolicyTypeDetail({
    id: policyType.id,
    userCollaboratorId: userCollaborator?.id,
    enabled: open && !!policyType.id,
  });

  const {
    drawer: conformationBalanceDrawer,
    showDrawer: showConformationBalanceDrawer,
  } = useDrawerV2(args =>
    getBalanceConformationDrawer({
      ...args,
      policyTypeDetail: detail!,
      userCollaborator: userCollaborator || user!,
    }),
  );

  const {
    drawer: policyDescriptionDrawer,
    showDrawer: showPolicyDescriptionDrawer,
  } = useDrawerV2(args =>
    getPolicyDescriptionDrawer({
      ...args,
      policyType,
      closePolicyTypeDrawer,
    }),
  );

  const { drawer: requestCreateDrawer, showDrawer: showRequestCreateDrawer } =
    useDrawerV2(args =>
      useCreateRequestDrawer({
        ...args,
        policyTypes: [policyType],
        user: userCollaborator || user!,
        isManagerRequesting: !isCollaboratorView,
        policyTypeSelected: { value: policyType.id, label: policyType.name },
        closePolicyTypeDrawer,
      }),
    );

  const handleShowRequestCreateDrawer = () => {
    showRequestCreateDrawer({});
  };

  const handleShowPolicyDescriptionDrawer = () => {
    showPolicyDescriptionDrawer({});
  };

  return {
    children: (
      <>
        {isLoading && <HuCircularProgress centered />}
        {!isLoading && detail && (
          <HuCardContainer
            sx={{
              width: '100%',
              '& .MuiCardContent-root': {
                pb: 0,
              },
            }}
          >
            {conformationBalanceDrawer}
            {policyDescriptionDrawer}
            {requestCreateDrawer}
            <HuTitle
              title={t('BALANCE_DETAILS')}
              variant="M"
            />
            <CardContent sx={{ px: 0 }}>
              <Divider />
              <Stack sx={{ py: 2, gap: 2 }}>
                <HuTitle
                  copetin={t('REQUEST_TYPE_ONE')}
                  variant="M"
                  title={policyType.name}
                />
                <HuTitle
                  copetin={t('CURRENT_CYCLE')}
                  variant="M"
                  title={`${formatDateInVacations({
                    date: detail.fromDateCycle,
                    user: user!,
                    type: 'P',
                  })} - ${formatDateInVacations({
                    date: detail.toDateCycle,
                    user: user!,
                    type: 'P',
                  })}`}
                />
                <HuTitle
                  copetin={t('TIME_USED')}
                  variant="M"
                  title={t(
                    detail.unit === UnitVacations.DAYS
                      ? 'TOTAL_DAYS'
                      : UnitVacations.HOURS,
                    {
                      count: detail.amountRequested,
                    },
                  )}
                />
                {detail.allowanceType === AllowanceType.BASIC_ANNUAL && (
                  <HuTitle
                    copetin={t('AVAILABLE_TIME')}
                    variant="M"
                    title={t(
                      detail.unit === UnitVacations.DAYS
                        ? 'TOTAL_DAYS'
                        : UnitVacations.HOURS,
                      {
                        count: detail.currentBalance,
                      },
                    )}
                  />
                )}
              </Stack>
            </CardContent>
            <Divider />
            <CardActions
              onClick={showConformationBalanceDrawer}
              sx={{ px: 0, py: 2 }}
            >
              <Button endIcon={<IconArrowRight />}>
                {t('VIEW_BALANCE_BREAKDOWN')}
              </Button>
            </CardActions>
          </HuCardContainer>
        )}
      </>
    ),
    title: policyType.name,
    ...(isCollaboratorView && {
      primaryButtonProps: {
        children: t('REQUEST'),

        onClick: handleShowRequestCreateDrawer,
        sx: { width: !policyType.description ? '100%' : undefined },
      },
    }),
    ...(policyType.description && {
      secondaryButtonProps: {
        children: t('POLICY_DESCRIPTION'),
        onClick: handleShowPolicyDescriptionDrawer,
      },
    }),
  };
};
