import React from 'react';
import { ArrayControlProps, UISchemaElement } from '@jsonforms/core';
import { JsonFormsDispatch } from '@jsonforms/react';
import {
 Typography,
 Box,
 Divider,
 useTheme,
 AccordionProps,
 styled,
 AccordionSummaryProps,
 Accordion,
 AccordionSummary,
 AccordionDetails,
} from '@mui/material';
import { isEmpty } from 'lodash';
import Grid from '@mui/material/Grid2';
import { isHidden } from '../common/getHiddenKeys';
import ArrowRightIcon from '@mui/icons-material/ArrowRight';

const StyledAccordion = styled((props: AccordionProps) => (
 <Accordion disableGutters elevation={0} square {...props} />
))(({ theme }) => ({
 border: `none`,
 // boxShadow: `-5px 2px 5px #00000029`,
}));

const StyledAccordionSummary = styled((props: AccordionSummaryProps) => (
 <AccordionSummary expandIcon={<ArrowRightIcon />} {...props} />
))(({ theme }) => ({
 flexDirection: 'row',
 justifyContent: 'start',
 border: 'none',
 '& .MuiAccordionSummary-expandIconWrapper': {
  '& .MuiSvgIcon-root': {
   fontSize: theme.typography.fontSize * 2.3,
   color: theme.palette.grey.A400,
  },
 },
 '& .MuiAccordionSummary-expandIconWrapper.Mui-expanded': {
  transform: 'rotate(90deg)',
 },
 '& .MuiAccordionSummary-content': {
  flexGrow: 0,
 },
}));

const WrapperContent = function WrapperContent({
 path,
 schema,
 elements,
 uischema,
 renderers,
 cells,
}: ArrayControlProps | any) {
 const theme = useTheme();
 const wrapperId = uischema?.config?.main?.wrapperId;
 return (
  <Grid
   id={`wrapper_${wrapperId}`}
   container
   rowSpacing={uischema.config?.main?.rowSpacing || 1}
   columnSpacing={uischema.config?.main?.columnSpacing || 2}
   spacing={uischema.config?.main?.spacing || 2}
   columns={{
    xs: uischema?.config?.layout?.xs || 12,
    sm: uischema?.config?.layout?.sm || 12,
    md: uischema?.config?.layout?.md || 12,
    lg: uischema?.config?.layout?.lg || 12,
   }}
   sx={{
    justifyContent: 'space-between',
    margin: '0',
    background: 'inherit',
    paddingLeft: theme.spacing(2),
    paddingRight: theme.spacing(2),
    paddingBottom: uischema.config?.main?.label
     ? uischema.config?.main?.isAccordion
       ? '10px'
       : 'auto'
     : 'auto',
    ...uischema?.config?.style?.componentsBoxStyle,
    ...uischema?.config?.componentsBoxStyle,
   }}
  >
   {!isEmpty(elements) &&
    elements.map((child: UISchemaElement | any, i: number) => {
     if (isHidden(child, schema)) {
      return null;
     }
     const updatedChild = {
      ...child,
      config: {
        ...child.config,
        main: {
          ...child.config?.main,
          additionalData: {
            ...child.config?.main?.additionalData,
            rowData: {
              ...uischema.config?.main?.additionalData?.rowData
            }
          }
        }
      }
    };
     return (
      <Grid
       key={i}
       id={`${wrapperId}-item-${i}`}
       sx={{
        // padding: "8px",
        display: {
         xs: child?.config?.layout?.xs === 0 ? 'none' : 'block',
         sm: child?.config?.layout?.sm === 0 ? 'none' : 'block',
         md: child?.config?.layout?.md === 0 ? 'none' : 'block',
         lg: child?.config?.layout?.lg === 0 ? 'none' : 'block',
        },
        ...uischema?.config?.style?.componentsBoxChildStyle,
       }}
       size={{
        xs: child?.config?.layout
         ? child?.config?.layout.xs
           ? child?.config?.layout.xs
           : child?.config?.layout
         : 12,

        sm: child?.config?.layout
         ? child?.config?.layout.sm
           ? child?.config?.layout.sm
           : child?.config?.layout
         : 12,

        md: child?.config?.layout
         ? child?.config?.layout.md
           ? child?.config?.layout.md
           : child?.config?.layout
         : 12,

        lg: child?.config?.layout
         ? child?.config?.layout.lg
           ? child?.config?.layout.lg
           : child?.config?.layout
         : 12,
       }}
      >
       <JsonFormsDispatch
        schema={schema}
        uischema={updatedChild}
        path={path}
        cells={cells}
        renderers={renderers}
       />
      </Grid>
     );
    })}
  </Grid>
 );
};

const AccordionWrapper = function AccordionWrapper({
 path,
 schema,
 elements,
 uischema,
 renderers,
 cells,
}: ArrayControlProps | any) {
 const theme = useTheme();
 const [expanded, setExpanded] = React.useState<string | false>(
  uischema?.config?.main?.defaultClosed ? false : 'panel',
 );

 const handleAccordionChange =
  (panel: string) => (event: React.SyntheticEvent, newExpanded: boolean) => {
   setExpanded(newExpanded ? panel : false);
  };
 return (
  <StyledAccordion
   expanded={expanded === 'panel'}
   onChange={handleAccordionChange('panel')}
   sx={{
    ...uischema?.config?.style?.accordionStyle,
   }}
  >
   <StyledAccordionSummary
    aria-controls='panel-content'
    id='panel-header'
    sx={{
     ...uischema?.config?.style?.accordianBoxStyle,
    }}
   >
    {uischema?.config?.main?.label && (
     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
      {uischema?.config?.main?.icon && (
       <Box
        sx={{
         display: 'flex',
         alignItems: 'center',
         justifyContent: 'center',
         borderRadius: '10px',
         padding: '7px',
         ...uischema?.config?.style?.iconBoxStyle,
        }}
       >
        <img
         src={uischema?.config?.main?.icon}
         alt='section-icon'
         style={{
          display: 'block',
          ...uischema?.config?.style?.iconStyle,
         }}
        />
       </Box>
      )}
      <Typography
       component={'div'}
       sx={{
        paddingLeft: '8px',
        fontSize: theme.typography.fontSize * (18 / 14),
        fontWeight: 'bold',
        color: 'inherit',
        ...uischema?.config?.style?.labelStyle,
       }}
      >
       {uischema.config?.main?.label}
      </Typography>
      {uischema?.config?.main?.divider && (
       <Divider sx={{ paddingTop: '8px' }} variant='fullWidth'></Divider>
      )}
     </Box>
    )}
   </StyledAccordionSummary>
   <AccordionDetails sx={{ padding: 0 }}>
    <WrapperContent
     path={path}
     schema={schema}
     elements={elements}
     uischema={uischema}
     renderers={renderers}
     cells={cells}
    />
   </AccordionDetails>
  </StyledAccordion>
 );
};

const DefaultWrapper = function DefaultWrapper({
 path,
 schema,
 elements,
 uischema,
 renderers,
 cells,
}: ArrayControlProps | any) {
 const theme = useTheme();
 return (
  <>
   {uischema?.config?.main?.label && (
    <Box>
     <Typography
      component={'div'}
      sx={{
       padding: '10px',
       paddingLeft: 3,
       fontSize: theme.typography.fontSize * (18 / 14),
       // fontFamily: "roboto",
       fontWeight: 'bold',
       color: 'inherit',
       ...uischema?.config?.style?.labelStyle,
      }}
     >
      {uischema.config?.main?.label}
     </Typography>
     {uischema?.config?.main?.divider && (
      <Divider sx={{ paddingTop: '8px' }} variant='fullWidth'></Divider>
     )}
    </Box>
   )}
   <WrapperContent
    path={path}
    schema={schema}
    elements={elements}
    uischema={uischema}
    renderers={renderers}
    cells={cells}
   />
  </>
 );
};

const WrapperContainer = {
 Accordion: AccordionWrapper,
 Default: DefaultWrapper,
};

const Wrapper = function Wrapper({
 path,
 schema,
 elements,
 uischema,
 renderers,
 cells,
}: ArrayControlProps | any) {
 const getWrapperType = (uischema: any) => {
  if (uischema?.config?.main?.isAccordion) {
   return 'Accordion';
  }
  return 'Default';
 };

 const GetWrapperComponent = WrapperContainer[getWrapperType(uischema)];
 return (
  <GetWrapperComponent
   path={path}
   schema={schema}
   elements={elements}
   uischema={uischema}
   renderers={renderers}
   cells={cells}
  />
 );
};

export default Wrapper;