import React from 'react';
import {
  Breadcrumbs,
  Heading,
  Page,
  PageHeaderProps,
  SkeletonRectangle,
  Box,
  Badge,
} from '@wix/design-system';
import { useFormPageContext } from '../../providers';
import { FormPageActionsBar } from '../../components/FormPage';
import { PageSubTitle, PageSubTitleProps } from '../../components/PageSubTitle';
import { st, classes } from './FormPageHeader.st.css.js';
import { useIsMobile } from '../../hooks/useIsMobile';
import { FormPageHeaderProps } from '../../components/FormPageHeader';

export function useFormPageHeader(
  child: JSX.Element,
  {
    headerProps = {},
    overrides = {},
  }: {
    headerProps?: PageHeaderProps;
    overrides?: {
      title?: FormPageHeaderProps['title'] | null;
      subtitle?: PageSubTitleProps | null;
      breadcrumbs?: React.ReactElement<Breadcrumbs> | null;
    };
  } = {},
) {
  const state = useFormPageContext();
  const isMobile = useIsMobile();
  const { title, subtitle, breadcrumbs } = overrides;

  const actionsBar = (
    <FormPageActionsBar moreActions={child.props.moreActions} />
  );

  const renderTitle = () => {
    if (!title?.text) {
      return <SkeletonRectangle height="24px" width="50%" />;
    }

    const { text, badges } = title;

    return (
      <Box gap="SP2" verticalAlign="middle" alignContent="center">
        <Heading size={isMobile ? 'large' : 'extraLarge'}>{text}</Heading>
        {badges && badges.length > 0 && (
          <Box gap="SP2">
            {badges.map((badge, index) => (
              <Badge
                key={index}
                {...badge}
                dataHook={`form-page-header-badge-${index}`}
              >
                {badge.text}
              </Badge>
            ))}
          </Box>
        )}
      </Box>
    );
  };

  return (
    <Page.Header
      className={st(classes.root, { mobile: isMobile })}
      key={child.key}
      title={renderTitle()}
      subtitle={
        !subtitle && state.isFetching ? (
          <SkeletonRectangle marginTop="SP1" height="12px" width="70%" />
        ) : (
          subtitle && <PageSubTitle {...subtitle} />
        )
      }
      actionsBar={actionsBar}
      breadcrumbs={breadcrumbs}
      {...headerProps}
    />
  );
}
