import React, { forwardRef, useMemo } from 'react';

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

import { getChipStyles, getLabelColor } from './style';
import { IChipProps } from './type';
const staticChipStyles = makeStyles((theme) => {
  return {
    relativeContainer: {
      position: 'relative',
    },
    root: {
      display: 'flex',
      alignSelf: 'baseline',
      flexDirection: 'row',
      alignItems: 'center',
      gap: theme?.spacing[2],
      paddingHorizontal: theme?.spacing[2],
    },
    prefixIconContainer: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    suffixIconContainer: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    topIconContainer: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    chipCountRoot: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: theme?.color.chip.selectedPrimaryLabel,
      height: theme?.size[4],
      minWidth: theme?.size[4],
      borderRadius: 50,
      borderColor: '#fff',
      top: 1,
      borderWidth: theme?.border.width.sm,
      paddingHorizontal: theme?.spacing[1],
      marginLeft: -theme?.spacing[2],
    },
    labelContainerStyles: {
      paddingLeft: theme?.spacing[1],
      paddingRight: theme?.spacing[1],
    },
  };
});

const ChipCounter = ({
  count,
  styleConfig,
}: {
  count: number;
  styleConfig: {
    root: Styles[];
    typography: TypographyStyleConfigProps;
  };
}) => {
  const { root = [], typography = {} } = styleConfig || {};
  return (
    <Container
      styleConfig={{
        root: [staticChipStyles.chipCountRoot, ...root],
      }}
    >
      <Typography variant='TAG' color='neutral' styleConfig={typography}>
        {count}
      </Typography>
    </Container>
  );
};

const Chip = forwardRef(
  (
    {
      id,
      label,
      onClick,
      size = 'sm',
      labelVariant = 'B2',
      isSelected = false,
      disabled = false,
      prefixIcon,
      suffixIcon,
      topIcon,
      styleConfig,
      showCounter,
      count = 0,
      isDismissible = false,
      onDismiss,
    }: IChipProps,
    ref: React.ForwardedRef<ContainerRef>,
  ) => {
    const theme = useTheme();
    const {
      relativeContainer: customRelativeContainerStyles = [],
      root: customRootStyles = [],
      labelContainer: customLabelContainerStyles = [],
      prefixIconContainer: customPrefixIconContainerStyles = [],
      suffixIconContainer: customSuffixIconContainerStyles = [],
      topIconContainer: customTopIconContainerStyles = [],
      counter: customChipCountRootStyles = [],
      counterTypography: customChipCountTypographyStyles = {},
    } = styleConfig || {};

    const labelColor = useMemo(() => {
      return getLabelColor(disabled);
    }, [disabled]);

    const isTopIcon = Boolean(topIcon);

    const chipStyles = useStyles(
      (theme) => {
        return {
          root: getChipStyles({
            theme,
            size,
            isDisabled: disabled,
            isSelected,
            topIcon: isTopIcon,
          }),
        };
      },
      [size, isSelected, disabled, isTopIcon],
    );

    const chipStylesForTopIcon = useStyles(
      (theme) => {
        if (topIcon) {
          return {
            root: {
              flexDirection: 'column',
              alignItems: 'flex-start',
              gap: theme?.spacing[0],
              borderRadius: theme?.border.radius[16],
            },
          };
        }
        return {};
      },
      [topIcon],
    );

    return (
      <Container
        styleConfig={{
          root: [staticChipStyles?.relativeContainer, ...customRelativeContainerStyles],
        }}
        id={id}
      >
        <Container
          ref={ref}
          onClick={onClick ? onClick : undefined}
          styleConfig={{
            root: [staticChipStyles?.root, chipStyles.root, chipStylesForTopIcon?.root, ...customRootStyles],
          }}
        >
          {!!topIcon && (
            <Container
              styleConfig={{
                root: [staticChipStyles?.topIconContainer, ...customTopIconContainerStyles],
              }}
            >
              {topIcon}
            </Container>
          )}
          {!!prefixIcon && (
            <Container
              styleConfig={{
                root: [staticChipStyles?.prefixIconContainer, ...customPrefixIconContainerStyles],
              }}
            >
              {prefixIcon}
            </Container>
          )}
          {!!label && (
            <Container
              styleConfig={{
                root: [staticChipStyles?.labelContainerStyles, ...customLabelContainerStyles],
              }}
            >
              {typeof label === 'string' ? (
                <Typography lineClamp={1} variant={labelVariant} color={labelColor}>
                  {label}
                </Typography>
              ) : (
                label
              )}
            </Container>
          )}
          {showCounter && !!count && (
            <ChipCounter
              count={count}
              styleConfig={{ root: customChipCountRootStyles, typography: customChipCountTypographyStyles }}
            />
          )}
          {!!suffixIcon && (
            <Container
              styleConfig={{
                root: [staticChipStyles?.suffixIconContainer, ...customSuffixIconContainerStyles],
              }}
            >
              {suffixIcon}
            </Container>
          )}
          {isDismissible && (
            <button
              onClick={() => {
                onDismiss?.();
              }}
            >
              <Cross
                height={16}
                width={16}
                crossColor={
                  isSelected ? theme.color.chip.selectedPrimaryLabel : theme.color.chip.nonSelectedPrimaryLabel
                }
              />
            </button>
          )}
        </Container>
      </Container>
    );
  },
);

Chip.displayName = 'Chip';

export default Chip;
