import React, {
  PropsWithChildren,
  ReactNode,
  useCallback,
  useMemo,
  useState,
} from 'react';
import {LayoutChangeEvent, View} from 'react-native';
import {Typography} from '@components/_core';

import {getTitleContainerStyle, styles} from './styles';
import {HeaderBox} from '../HeaderBox';
import {SubheaderChips, SubheaderSearch, SubheaderTabs} from '../Subheader';

interface HeaderSectionProps extends PropsWithChildren {
  leftComponent?: ReactNode;
  title?: string | ReactNode;
  rightComponent?: ReactNode;
  hasTopSafeArea?: boolean;
  hideBorder?: boolean;
}

export function HeaderSection({
  leftComponent,
  title,
  rightComponent,
  hasTopSafeArea = false,
  hideBorder = false,
  children,
}: HeaderSectionProps) {
  const [contentWidth, setContentWidth] = useState(0);
  const titleContainerStyle = useMemo(
    () => getTitleContainerStyle(contentWidth),
    [contentWidth],
  );

  const onHeaderBoxLayout = useCallback((event: LayoutChangeEvent) => {
    setContentWidth(event.nativeEvent.layout.width);
  }, []);

  return (
    <>
      <HeaderBox
        hasTopSafeArea={hasTopSafeArea}
        hideBorder={hideBorder}
        onLayout={onHeaderBoxLayout}>
        <View style={styles.sideContainer}>{leftComponent}</View>
        <View style={titleContainerStyle}>
          {typeof title === 'string' ? (
            <Typography
              weight="semiBold"
              align="center"
              numberOfLines={1}
              maxFontSizeMultiplier={1}>
              {title}
            </Typography>
          ) : (
            title
          )}
        </View>
        <View style={[styles.sideContainer, styles.rightContainer]}>
          {rightComponent}
        </View>
      </HeaderBox>
      {children}
    </>
  );
}

HeaderSection.SubheaderChips = SubheaderChips;
HeaderSection.SubheaderSearch = SubheaderSearch;
HeaderSection.SubheaderTabs = SubheaderTabs;
