"use client";

import React, { forwardRef } from "react";
import { cx } from "../../utils/cx";
import { ListItem, ListItemProps } from "./list-item";
import { ListProps } from "./types";

export const List = forwardRef<HTMLUListElement | HTMLOListElement, ListProps>(
  (
    {
      type = "ul",
      items,
      className = "",
      renderItem,
      children,
      variant = "unstyled",
      style,
      ...props
    },
    ref
  ) => {
    // Get Tailwind classes for different variants
    const getVariantClasses = () => {
      if (variant === "unstyled") {
        return "";
      }

      // TODO: Add styles based on the figma design for all variants
      const baseClasses = "m-0 p-0";
      const typeClasses =
        type === "ol" ? "pl-6 list-decimal" : "pl-5 list-disc";

      return `${baseClasses} ${typeClasses}`;
    };

    const tailwindClasses = getVariantClasses();
    const combinedClassName = cx(
      tailwindClasses,
      `list--${type}`,
      `list--${variant}`,
      className
    );

    // Render items if provided
    const renderItems = () => {
      if (!items || items.length === 0) return null;

      return items.map((item, index) => {
        if (renderItem) {
          return renderItem(item, index);
        }

        return (
          <ListItem
            key={item.id || index}
            className={item.className}
            variant={variant}
          >
            {item.content}
          </ListItem>
        );
      });
    };

    const content = children || renderItems();

    // Create props object to avoid duplication
    const listProps = {
      className: combinedClassName,
      style,
      ...props,
      children: content,
    };

    // Return appropriate list type with conditional rendering for proper TypeScript inference
    if (type === "ol") {
      return (
        <ol
          {...listProps}
          ref={ref as React.Ref<HTMLOListElement>}
          role="list"
        />
      );
    }

    return (
      <ul {...listProps} ref={ref as React.Ref<HTMLUListElement>} role="list" />
    );
  }
);

List.displayName = "List";

export { ListItem };

export type { ListProps, ListItemProps };
