import { useState } from 'react';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography/Typography';

import { useDialogLayerItem } from '@material-hu/components/layers/Dialogs';

import {
  type ApprovableStatus,
  TimeTrackingCategorizedHourStatus,
} from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type BulkReviewBreakdownItem } from '../utils';

const BULK_DIALOG_COPY_KEYS: Record<
  ApprovableStatus,
  { title: string; intro: string; confirm: string }
> = {
  [TimeTrackingCategorizedHourStatus.APPROVED]: {
    title: 'approval_requests:bulk_actions.want_to_approve_requests',
    intro: 'bulk_overtime_approvals.about_to_approve',
    confirm: 'approval_requests:bulk_actions.approve_confirm',
  },
  [TimeTrackingCategorizedHourStatus.REJECTED]: {
    title: 'approval_requests:bulk_actions.want_to_reject_requests',
    intro: 'bulk_overtime_approvals.about_to_reject',
    confirm: 'approval_requests:bulk_actions.reject_confirm',
  },
};

type UseBulkReviewDialogArgs = {
  bulkSelectedCount: number;
  breakdown: BulkReviewBreakdownItem[];
  isSubmitting: boolean;
  onConfirm: (status: ApprovableStatus) => void;
  onClose?: () => void;
};

export const useBulkReviewDialog = ({
  bulkSelectedCount,
  breakdown,
  isSubmitting,
  onConfirm,
  onClose,
}: UseBulkReviewDialogArgs) => {
  const { t } = useLokaliseTranslation(['time_tracker', 'approval_requests']);
  const [status, setStatus] = useState<ApprovableStatus | null>(null);

  const handleClose = () => {
    if (isSubmitting) return;
    setStatus(null);
    onClose?.();
    closeDialog();
  };

  const buildConfig = (s: ApprovableStatus) => {
    const keys = BULK_DIALOG_COPY_KEYS[s];
    return {
      title: t(keys.title, { count: bulkSelectedCount }),
      body: (
        <Stack sx={{ gap: 1 }}>
          <Typography
            variant="globalS"
            sx={{ color: theme => theme.palette.new.text.neutral.default }}
          >
            {t(keys.intro, { count: bulkSelectedCount })}
          </Typography>
          <Stack
            component="ul"
            sx={{
              m: 0,
              pl: 3,
              gap: 0.5,
              listStyleType: 'disc',
            }}
          >
            {breakdown.map(item => (
              <Typography
                key={item.hourCategoryId}
                component="li"
                variant="globalS"
                sx={{
                  color: theme => theme.palette.new.text.neutral.default,
                  display: 'list-item',
                }}
              >
                {t('bulk_overtime_approvals.breakdown_item', {
                  count: item.count,
                  category: item.hourCategoryName,
                })}
              </Typography>
            ))}
          </Stack>
        </Stack>
      ),
      primaryButtonProps: {
        children: t(keys.confirm, { count: bulkSelectedCount }),
        onClick: () => onConfirm(s),
        loading: isSubmitting,
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: handleClose,
        disabled: isSubmitting,
      },
      onClose: handleClose,
      disableCloseOnBackdropClick: isSubmitting,
      disableCloseOnEscapeKeyDown: isSubmitting,
      dialogProps: { maxWidth: 'sm' as const, fullWidth: true },
    };
  };

  // While the dialog is closed the config built here isn't user-visible; the
  // APPROVED fallback is just a placeholder so the hook always has a valid
  // status to render against. Once open, the reactive sync keeps it in step
  // with whatever status was passed to openFor.
  const { openDialog, closeDialog } = useDialogLayerItem(
    'bulk-review-dialog',
    buildConfig(status ?? TimeTrackingCategorizedHourStatus.APPROVED),
  );

  const openFor = (s: ApprovableStatus) => {
    setStatus(s);
    openDialog(buildConfig(s));
  };

  const close = () => {
    setStatus(null);
    closeDialog();
  };

  return { openFor, close };
};
