import { forwardRef, LegacyRef } from "react";
import { createBlockComponent, IBlockProps } from "#components/meta";

import * as styles from "./list.module.scss"

export type IListProps =
  | ({ isOrdered: true } & IListOrderedProps)
  | IListUnorderedProps;
interface IListUnorderedProps extends IBlockProps<"ul"> {}
interface IListOrderedProps extends IBlockProps<"ol"> {}
interface IListItemProps extends IBlockProps<"li"> {}

export const List = forwardRef<HTMLUListElement | HTMLOListElement, IListProps>(
  createBlockComponent(undefined, ListComponent)
);

export const ListUnordered = forwardRef<HTMLUListElement, IListUnorderedProps>(
  createBlockComponent(undefined, ListUnorderedComponent)
);

export const ListOrdered = forwardRef<HTMLOListElement, IListOrderedProps>(
  createBlockComponent(styles.ordered, ListOrderedComponent)
);

export const ListItem = forwardRef<HTMLLIElement, IListItemProps>(
  createBlockComponent(undefined, ListItemComponent)
);

function ListComponent(
  props: IListProps,
  ref: LegacyRef<HTMLUListElement | HTMLOListElement>
) {
  if ("isOrdered" in props) {
    const { isOrdered, ...restProps } = props;

    return (
      <ListOrdered ref={ref as LegacyRef<HTMLOListElement>} {...restProps} />
    );
  }

  return <ListUnordered ref={ref} {...props} />;
}

function ListUnorderedComponent(
  { ...props }: IListUnorderedProps,
  ref: LegacyRef<HTMLUListElement>
) {
  return <ul ref={ref} {...props} />;
}

function ListOrderedComponent(
  { ...props }: IListOrderedProps,
  ref: LegacyRef<HTMLOListElement>
) {
  return <ol ref={ref} {...props} />;
}

function ListItemComponent(
  { ...props }: IListItemProps,
  ref: LegacyRef<HTMLLIElement>
) {
  return <li ref={ref} {...props} />;
}
