import { Children, ReactElement, ReactNode, isValidElement, useMemo } from 'react';
import { Box, Button, Divider, Grid, useTheme } from '@mui/material';
import { MainCard } from '@/components/MainCard';
import { Toolbar } from './Toolbar';
import { useTranslate } from 'react-admin';
import _ from 'lodash';
import { useWizardFormContext } from './Provider';
import { Stepper } from './Stepper';
import { walkChildren } from '@/utils';

interface ContentProps {
  title?: ReactNode | string;
  subheader?: ReactNode | string;
  secondary?: ReactNode | string;
  toolbar?: ReactElement;
  progress?: ReactNode;
  isSmall: boolean;
  modal: boolean;
  sx?: any;
  setCurrentStep: (step: number) => void;
}

function Content({ title, subheader, secondary, toolbar, progress, isSmall, modal, sx, setCurrentStep }: ContentProps) {
  const { currentStep, steps } = useWizardFormContext();
  const translate = useTranslate();
  const theme = useTheme();
  const isHorizontal = isSmall || modal;

  const cancelButton = useMemo(() => {
    if (!toolbar) return null;

    return Children.toArray(toolbar.props.children).find(
      (child) =>
        isValidElement(child) && child.type === Button && child.props?.children === translate('ra.action.cancel')
    );
  }, [toolbar, translate]);

  const stepFields: Array<Array<string>> = steps.map((step: ReactElement) => {
    const fields: Array<string> = [];
    const { sources } = step.props;
    if (sources !== undefined) {
      fields.push(...sources);
    } else {
      walkChildren(step, (el) => {
        if (el?.props?.source !== undefined) {
          fields.push(el.props.source);
        }
      });
    }
    return fields;
  });

  return (
    <Grid container spacing={2} sx={sx}>
      <Grid item xl={modal ? 12 : 2} lg={modal ? 12 : 3} md={modal ? 12 : 3} sm={modal ? 12 : 4} xs={12}>
        {progress || <Stepper isHorizontal={isHorizontal} setCurrentStep={setCurrentStep} stepFields={stepFields} />}
      </Grid>
      {modal ? <Divider sx={{ width: '100%' }} /> : null}
      <Grid
        item
        xl={modal ? 12 : 10}
        lg={modal ? 12 : 9}
        md={modal ? 12 : 9}
        sm={modal ? 12 : 8}
        xs={12}
        sx={{ paddingTop: modal ? '0 !important' : null }}
      >
        <MainCard
          title={title || steps[currentStep].props.label}
          subheader={subheader}
          secondary={secondary}
          border={!modal}
          divider
        >
          <Box>{steps[currentStep]}</Box>
          <Box
            sx={{
              '& .MuiToolbar-root': {
                paddingLeft: 0,
                paddingRight: 0,
                paddingBottom: 0,
                paddingTop: theme.spacing(2)
              }
            }}
          >
            {toolbar && !cancelButton ? toolbar : <Toolbar cancelButton={cancelButton} />}
          </Box>
        </MainCard>
      </Grid>
    </Grid>
  );
}

export { Content };
