"use client";

import cx from "classnames";
import React, { useMemo } from "react";

import { useStatic } from "../../utils/hooks";
import { Icon } from "../Icon";

import ExpanderStatic from "./Expander.static";

const CLASS_ROOT = "expander";

interface ExpanderProps {
  /** Custom summary text renderer. Passes props as function parameter. */
  renderSummary?: (props: ExpanderProps) => React.ReactNode;
  /** Custom summary text renderer when details are opened. Passes props as function parameter. */
  renderSummaryOpened?: (props: ExpanderProps) => React.ReactNode;
  /** Trigger text */
  summary?: string;
  /** Trigger text when details are opened */
  summaryOpened?: string;
  /** Additional CSS classes */
  className?: string;
  /** Child elements */
  children?: React.ReactNode;
  /** Expander takes full width of its container */
  isFullWidth?: boolean;
  /** Position of trigger relative to content when opened */
  placement?: "top" | "bottom";
  /** Group identifier for syncing multiple expanders together */
  toggleGroup?: string;
  /** Initial open state */
  open?: boolean;
}

export const Expander: React.FC<ExpanderProps> = (props) => {
  const {
    className,
    children,
    summary,
    summaryOpened,
    renderSummary,
    renderSummaryOpened,
    isFullWidth,
    placement = "bottom",
    toggleGroup,
    ...other
  } = props;
  const [expanderRef] = useStatic(ExpanderStatic);

  const classes = cx(
    CLASS_ROOT,
    {
      [`${CLASS_ROOT}--fullwidth`]: isFullWidth,
      [`${CLASS_ROOT}--placement-top`]: placement === "top",
    },
    className,
  );

  const summaryText = useMemo(
    () =>
      renderSummary
        ? renderSummary(props)
        : summary && (
            <>
              {summary}{" "}
              <Icon alt="stav" name="chevron-down" data-summary-icon />
            </>
          ),
    [renderSummary, props, summary],
  );

  const summaryOpenedText = useMemo(
    () =>
      renderSummaryOpened
        ? renderSummaryOpened(props)
        : summaryOpened && (
            <>
              {summaryOpened}{" "}
              <Icon alt="stav" name="chevron-down" data-summary-icon />
            </>
          ),
    [renderSummaryOpened, props, summaryOpened],
  );

  return (
    <details
      className={classes}
      data-expander
      {...(toggleGroup ? { "data-toggle-group": toggleGroup } : {})}
      ref={expanderRef}
      {...other}
    >
      <summary data-summary={summary} data-summary-opened={summaryOpened}>
        <span className={`${CLASS_ROOT}__summary`}>{summaryText}</span>
        {summaryOpenedText && (
          <span className={`${CLASS_ROOT}__summary--opened`}>
            {summaryOpenedText}
          </span>
        )}
      </summary>
      <div>{children}</div>
    </details>
  );
};

Expander.displayName = "Expander";
