import { type ReactNode, useCallback, useLayoutEffect, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import { IconX } from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Modal from '@material-hu/mui/Modal';
import Stack from '@material-hu/mui/Stack';
import { alpha } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { useLokaliseTranslation } from 'src/utils/i18n';

import MarkdownContent from 'src/components/MarkdownContent';

import { RequestOfferActions } from './RequestOfferActions';

export type TermsModalProps = {
  open: boolean;
  onClose: () => void;

  contractMarkdown: string;

  contractLoading?: boolean;
};

export const TermsModal = ({
  open,
  onClose,
  contractMarkdown,
  contractLoading = false,
}: TermsModalProps) => {
  const { t } = useLokaliseTranslation('loans');
  const [scrollRoot, setScrollRoot] = useState<HTMLElement | null>(null);

  const [sentinelRef, inView] = useInView({
    root: scrollRoot ?? undefined,
    threshold: 0,
    initialInView: false,
    rootMargin: '0px 0px 8px 0px',
  });

  const setScrollContainerRef = useCallback((node: HTMLDivElement | null) => {
    setScrollRoot(node);
  }, []);

  useLayoutEffect(() => {
    if (scrollRoot) {
      scrollRoot.scrollTop = 0;
    }
  }, [scrollRoot]);

  const hasReachedEnd =
    open && !contractLoading && scrollRoot != null && inView;

  let bodyContent: ReactNode;
  if (contractLoading) {
    bodyContent = (
      <Stack sx={{ alignItems: 'center', justifyContent: 'center', py: 6 }}>
        <CircularProgress size={32} />
      </Stack>
    );
  } else if (contractMarkdown) {
    bodyContent = <MarkdownContent markdown={contractMarkdown} />;
  } else {
    bodyContent = (
      <Typography
        variant="globalXS"
        sx={{
          color: theme => theme.palette.new.text.neutral.lighter,
          lineHeight: 1.55,
        }}
      >
        {t('legal.contract_unavailable')}
      </Typography>
    );
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      aria-labelledby="microloans-terms-modal-title"
      aria-describedby="microloans-terms-modal-body"
      slotProps={{
        backdrop: {
          sx: theme => ({
            backgroundColor: alpha(theme.palette.common.black, 0.5),
          }),
        },
      }}
    >
      <Stack
        role="document"
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 'calc(100% - 32px)',
          maxWidth: 720,
          maxHeight: 'min(85vh, 640px)',
          outline: 'none',
        }}
      >
        <HuCardContainer
          fullWidth
          padding={0}
          sx={{
            flex: 1,
            minHeight: 0,
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            '& > .MuiCardContent-root': {
              p: 1,
              display: 'flex',
              flexDirection: 'column',
              flex: 1,
              minHeight: 0,
              overflow: 'hidden',
            },
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexShrink: 0,
              px: 2,
              py: 1.5,
              borderBottom: 1,
              borderColor: theme => theme.palette.new.border.neutral.divider,
            }}
          >
            <Typography
              id="microloans-terms-modal-title"
              component="h2"
              variant="globalM"
              sx={{
                fontWeight: 'fontWeightBold',
                color: theme => theme.palette.new.text.neutral.default,
              }}
            >
              {t('legal.terms_modal_title')}
            </Typography>
            <IconButton
              type="button"
              aria-label={String(t('legal.close_modal_aria'))}
              onClick={onClose}
              size="small"
              sx={{
                color: theme => theme.palette.new.text.neutral.lighter,
              }}
            >
              <IconX
                size={20}
                stroke={2}
              />
            </IconButton>
          </Stack>

          <Stack
            ref={setScrollContainerRef}
            id="microloans-terms-modal-body"
            sx={{
              flex: 1,
              minHeight: 0,
              overflowY: 'auto',
              px: 2.5,
              py: 2,
              textAlign: 'left',
            }}
          >
            {bodyContent}
            {open && !contractLoading && (
              <Stack
                ref={sentinelRef}
                aria-hidden
                sx={{
                  height: 4,
                  width: '100%',
                  flexShrink: 0,
                  pointerEvents: 'none',
                }}
              />
            )}
          </Stack>

          <Stack
            sx={{
              flexShrink: 0,
              p: 2,
              pt: 2,
              borderTop: 1,
              borderColor: theme => theme.palette.new.border.neutral.divider,
            }}
          >
            <RequestOfferActions
              layout="column"
              actions={[
                {
                  label: t('success.close'),
                  variant: 'primary',
                  fullWidth: true,
                  disabled: contractLoading || !hasReachedEnd,
                  onClick: onClose,
                },
              ]}
            />
          </Stack>
        </HuCardContainer>
      </Stack>
    </Modal>
  );
};
