import type { Responsive } from '@radix-ui/themes/props';
import React, { createContext, useContext, useMemo } from 'react';
import { clsx } from 'clsx';
import { mapWithResponsive } from '@/utils/map-with-responsive';
import { Typo } from './typo';
import { Flex } from './flex';

export interface ListRootProps {
  variant?: 'ol' | 'ul';
  size?: Responsive<'small' | 'large'>;
  children?: React.ReactNode;
  preSpace?: 'regular' | 'small';
  className?: string;
  style?: React.CSSProperties;
}

function Root(props: ListRootProps): React.ReactElement {
  const {
    variant,
    size = 'large',
    children,
    preSpace,
    className: propsClassName,
    ...rest
  } = props;
  const Comp = variant === 'ol' ? 'ol' : 'ul';

  const className = useMemo(
    () =>
      clsx(
        {
          'pre-space-small': preSpace === 'small',
        },
        propsClassName
      ),
    [preSpace, propsClassName]
  );

  return (
    <ListContext.Provider value={{ size }}>
      <Flex asChild direction="column" gap="1" {...rest} className={className}>
        <Comp>{children}</Comp>
      </Flex>
    </ListContext.Provider>
  );
}

export interface ListItemProps {
  children?: React.ReactNode;
}

function Item(props: ListItemProps): React.ReactElement {
  const { children } = props;
  const { size } = useList();

  const variant = useMemo(() => {
    return mapWithResponsive({
      value: size,
      mapFn: (sizeValue) => {
        return sizeValue === 'small' ? 'caption' : 'body';
      },
    });
  }, [size]);

  return (
    <Typo asChild variant={variant}>
      <li>{children}</li>
    </Typo>
  );
}

const ListContext = createContext<{ size: Responsive<'small' | 'large'> }>({
  size: 'large',
});

export function useList(): { size: Responsive<'small' | 'large'> } {
  return useContext(ListContext);
}

export const List = {
  Root,
  Item,
};
