import { type ReactElement, type ReactNode, cloneElement } from "react";
import { cx } from "../class-names.ts";
import { MiddotSeparated } from "../MiddotSeparated/MiddotSeparated.tsx";
import { item, list } from "./style.css.ts";

export { listViewTheme } from "./style.css.ts";

export function ListItemContainer(props: {
  children?: ReactNode;
  className?: string;
}) {
  return <li {...cx(props, item.container)}>{props.children}</li>;
}

export function ListItemContent(props: {
  children?: ReactNode;
  render?: ReactElement;
  className?: string;
}) {
  const element = props.render ?? <div />;
  return cloneElement(element, cx(props, item.content), props.children);
}

export function ListItemHeading(props: {
  children?: ReactNode;
  className?: string;
}) {
  return <div {...cx(props, item.heading)}>{props.children}</div>;
}

export function ListItemSummary(props: {
  children?: ReactNode;
  className?: string;
}) {
  return (
    <MiddotSeparated {...cx(props, item.summary)}>
      {props.children}
    </MiddotSeparated>
  );
}

export function ListItem(props: {
  heading: string;
  type?: string;
  summary: ReactNode;
  render?: ReactElement;
  aside?: ReactNode;
}) {
  const { render, heading, type, summary, aside } = props;

  return (
    <ListItemContainer>
      <ListItemContent render={render}>
        <ListItemHeading>{heading}</ListItemHeading>

        <ListItemSummary>
          {type && <em>{type}</em>}
          {summary}
        </ListItemSummary>
      </ListItemContent>

      {aside}
    </ListItemContainer>
  );
}

export function ListView(props: {
  children?: ReactNode;
  fallback?: ReactNode;
  className?: string;
}) {
  const { children, fallback } = props;

  return (
    <>
      <ul {...cx(props, list.container)}>{children}</ul>
      <div className={list.empty}>{fallback}</div>
    </>
  );
}
