import React, { ReactNode, useContext } from 'react';

import { Container } from '@cleartrip/ct-design-container';
import { Cross } from '@cleartrip/ct-design-icons';
import { useStyles } from '@cleartrip/ct-design-style-manager';
import { useTheme } from '@cleartrip/ct-design-theme';
import { Typography, TypographyStyleConfigProps } from '@cleartrip/ct-design-typography';
import type { Styles } from '@cleartrip/ct-design-types';

import ModalContext from '../ModalContext';
import { ModalProps } from '../type';
import { ModalSize } from '../constants';

type ModalTitleStyleConfig = {
  root?: Styles[];
  iconContainer?: Styles[];
  childrenTypography?: TypographyStyleConfigProps;
  crossIcon?: React.SVGProps<SVGSVGElement>;
};

type ModalTitleProps = Pick<ModalProps, 'hideCrossIcon' | 'onClose'> & {
  children: ReactNode;
  styleConfig?: ModalTitleStyleConfig;
};

const ModalTitle: React.FunctionComponent<ModalTitleProps> = ({ children, styleConfig }) => {
  const theme = useTheme();
  const { hideCrossIcon, onClose, size } = useContext(ModalContext);
  const isFullScreen = size === ModalSize.FULL_SCREEN;

  const rootStyles = useStyles(
    (t) => ({
      root: {
        display: 'flex',
        justifyContent: 'space-between',
        paddingTop: isFullScreen ? t.spacing[5] : t.spacing[6],
        paddingBottom: isFullScreen ? t.spacing[5] : t.spacing[4],
        paddingLeft: isFullScreen ? t.spacing[7] : t.spacing[6],
        paddingRight: isFullScreen ? t.spacing[7] : t.spacing[6],
        boxShadow: t.elevation.bottomE1,
      },
      iconContainer: {
        cursor: 'pointer',
        marginTop: t.spacing[1],
        marginRight: t.spacing[1],
      },
    }),
    [isFullScreen],
  );

  return (
    <Container styleConfig={{ root: [rootStyles.root, ...(styleConfig?.root ?? [])] }}>
      <Typography variant='HM2' styleConfig={styleConfig?.childrenTypography}>
        {children}
      </Typography>
      {!hideCrossIcon && (
        <Container
          onClick={onClose}
          styleConfig={{
            root: [rootStyles.iconContainer, ...(styleConfig?.iconContainer ?? [])],
          }}
        >
          <Cross height={24} width={24} crossColor={theme.color.text.heading} {...styleConfig?.crossIcon} />
        </Container>
      )}
    </Container>
  );
};

export default ModalTitle;
