import { useBool } from '@redneckz/uni-jsx/lib/hooks/useBool';
import { BlockWrapper } from '../../ui-kit/BlockWrapper';
import { DefaultFoldButton } from '../../ui-kit/Foldable/DefaultFoldButton';
import { Foldable } from '../../ui-kit/Foldable/Foldable';
import { FoldableSection } from '../../ui-kit/Foldable/FoldableSection';
import { UniBlock } from '../../UniBlock/UniBlock';
import { type UniBlockProps } from '../../UniBlock/UniBlockProps';
import { style } from '../../utils/style';
import { Headline } from '../Headline/Headline';
import { type TariffsTableContent } from './TariffsTableContent';
import { TariffsTableRow } from './TariffsTableRow';
import { TariffsTableWrapper } from './TariffsTableWrapper';

export interface TariffsTableProps extends TariffsTableContent, UniBlockProps {}

export const TariffsTable = UniBlock<TariffsTableProps>(
  ({
    className = '',
    title,
    description,
    rowHeaders,
    tariffsColumns: columns,
    hiddenRowsNum = 0,
    ...rest
  }) => {
    const colData = columns?.map(({ data }) => data) || [];
    const rowData = rowHeaders?.map((header, i) => ({
      header,
      data: colData.map((col) => col?.[i] || []),
    }));
    const rows = (rowData || []).map((row, i) => (
      <TariffsTableRow key={String(i)} row={row} {...rest} />
    ));
    const [visibleRows, hiddenRows] =
      hiddenRowsNum > 0 ? [rows.slice(0, -hiddenRowsNum), rows.slice(-hiddenRowsNum)] : [rows, []];

    const [isUnfolded, { toggle }] = useBool(false);

    return (
      <BlockWrapper
        className={style('relative space-y-xl', className)}
        defaultPadding="p-6xl"
        {...rest}
      >
        <Headline
          title={title}
          description={description}
          headlineVersion="M"
          isEmbedded={true}
          align="text-center"
        />
        <div className="space-y-m overflow-hidden">
          {hiddenRowsNum > 0 ? (
            <Foldable>
              <TariffsTableWrapper>
                {visibleRows}
                <FoldableSection isUnfolded={isUnfolded} isOverflowVisible={true}>
                  {hiddenRows}
                </FoldableSection>
              </TariffsTableWrapper>
              <DefaultFoldButton className="text-h4" isUnfolded={isUnfolded} onClick={toggle} />
            </Foldable>
          ) : (
            <TariffsTableWrapper>{rows}</TariffsTableWrapper>
          )}
        </div>
      </BlockWrapper>
    );
  },
);
