import React, {
  PropsWithChildren,
  ReactNode,
  useEffect,
  useMemo,
  useState,
} from 'react';
import {View, Image as RNImage, ImageStyle} from 'react-native';
import HumandLogo from '@assets/humand.svg';
import {Image} from '@components/_core/Image';
import {useInstanceProp} from '@redux/selectors';

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

interface HeaderHomeProps extends PropsWithChildren {
  rightContent?: ReactNode;
}

export function HeaderHome({children, rightContent}: HeaderHomeProps) {
  const [logoAspectRatio, setLogoAspectRatio] = useState(0);
  const logo = useInstanceProp('logo');
  const isLogoInfoLoaded = logo && !!logoAspectRatio;
  const logoStyle = useMemo(
    () => getLogoStyle(logoAspectRatio),
    [logoAspectRatio],
  );

  useEffect(() => {
    logo &&
      RNImage.getSize(logo, (width, height) => {
        setLogoAspectRatio(width / height);
      });
  }, [logo]);

  return (
    <>
      <HeaderBox>
        {isLogoInfoLoaded ? (
          <Image
            style={logoStyle}
            source={{uri: logo}}
            contentFit="contain"
            enableCache
          />
        ) : (
          <HumandLogo
            width={(logoStyle as ImageStyle)?.width as number}
            height={(logoStyle as ImageStyle)?.height as number}
          />
        )}
        <View style={styles.rightContainer}>{rightContent}</View>
      </HeaderBox>
      {children}
    </>
  );
}

HeaderHome.SubheaderChips = SubheaderChips;
HeaderHome.SubheaderSearch = SubheaderSearch;
HeaderHome.SubheaderTabs = SubheaderTabs;
