import {
 Accordion,
 AccordionDetails,
 AccordionSummary,
 Box,
 IconButton,
 Typography,
} from '@mui/material';
import React, { useContext, useEffect } from 'react';
import Grid from '@mui/material/Grid2';
import { JsonFormsDispatch, useJsonForms } from '@jsonforms/react';
import { ButtonIcon } from '../../common/ButtonIcon';
import { composePaths } from '@jsonforms/core';
import { DataContext } from '../../context/Context';
import _ from 'lodash';

const ArrayLayoutRenderer = (props) => {
 const {
  uischema,
  schema,
  path,
  renderers,
  enabled,
  cells,
  index,
  theme,
  handleDelete,
  arrayExpendState,
  componentStyle
 } = props;
 const { handleToggleArray = {} } = useContext(DataContext);
 const [expanded, setExpanded] = React.useState(
  arrayExpendState?.[path] ?? false,
 );
 const ctx = useJsonForms();
 const childPath = composePaths(path, `${index}`);
 console.log(schema);
 useEffect(() => {
  if (arrayExpendState[path] !== null) {
   setExpanded(arrayExpendState[path] ?? false);
  }
 }, [arrayExpendState[path]]);
 console.log(arrayExpendState[path]);
 return (
  <Accordion
   key={`${path}-${index}`}
   expanded={expanded}
   onChange={() => {
    setExpanded((prev) => !prev);
    handleToggleArray(path, null);
   }}
   sx={{
    marginTop: 1,
    padding: { xs: '4px 2px', md: '6px 4px' },
    borderRadius: '6px',
    boxShadow: '0px 1px 3px rgba(0,0,0,0.25)',
    '::before': { display: 'none' },
    ...componentStyle?.childAccordionStyle,
   }}
  >
   <AccordionSummary
    sx={{
     minHeight: 0,
     margin: '2px 0px',
     '&.Mui-expanded': { minHeight: 0 },
     '& .MuiAccordionSummary-content': { margin: 0 },
     '& .MuiAccordionSummary-content.Mui-expanded': { margin: '4px 0px' },
     ...componentStyle?.childAccordionSummaryStyle,
    }}
    
   >
    {!uischema.config.main?.disableRowActions && (
     <Grid
      sx={{
       display: 'flex',
       alignItems: 'center',
       justifyContent: 'space-between',
       width: '100%',
       padding: '0',
       margin: 0,
       ...uischema.config?.style?.rowActionsStyle,
      }}
     >
      {/* Left */}
      <Grid
       sx={{
        display: 'flex',
        alignItems: 'center',
        gap: 1,
       }}
      >
       <Box
        sx={{
         width: 20,
         height: 20,
         borderRadius: '50%',
         display: 'flex',
         alignItems: 'center',
         justifyContent: 'center',
         border: '1.5px solid #767676',
         fontSize: {
          xs: theme.myTheme.typography.fontSize * 0.9,
          md: theme.myTheme.typography.fontSize * 1.1,
          lg: theme.myTheme.typography.fontSize * 1.2,
         },
         fontWeight: 500,
         ...uischema.config.style?.childElementIndexStyle,
        }}
       >
        {index + 1}
       </Box>

       <Typography
        sx={{
         fontSize: {
          xs: theme.myTheme.typography.fontSize * 1,
          md: theme.myTheme.typography.fontSize * 1.2,
          lg: theme.myTheme.typography.fontSize * 1.3,
         },
         ...uischema.config.style?.childElementLabelStyle,
        }}
       >
        {uischema.config.main?.showKeyAsLabel
         ? ctx.core.data?.[path]?.[index]?.[
            uischema.config.main?.showKeyAsLabel
           ]
         : uischema.config.main?.childElementLabel}
       </Typography>
      </Grid>
      <Grid sx={{ display: 'flex', gap: 0.5 }}>
       <IconButton
        size='small'
        key={`delete-${index}`}
        disableRipple
        onClick={(e) => {
         e.preventDefault();
         e.stopPropagation();
         handleDelete(index);
        }}
        sx={{
         fill: theme.myTheme.palette.common.black,
         '&:hover': { fill: theme.myTheme.palette.primary.main },
         display: ctx.core.data?.[path]?.[index]?.disableDelete
          ? 'none'
          : 'inline-block',
         ...uischema.config.style?.rowDeleteButtonStyle,
        }}
       >
        {ButtonIcon('Bin', {})}
       </IconButton>
      </Grid>
     </Grid>
    )}
   </AccordionSummary>

   <AccordionDetails sx={{ paddingBottom: 0, paddingTop: '2px' }}>
    <Grid
     container
     rowSpacing={uischema.config?.main?.rowSpacing || 1}
     columnSpacing={uischema.config?.main?.columnSpacing || 2}
     spacing={uischema.config?.main?.spacing || 1}
     sx={{
      gap: 1,
      justifyContent: 'space-between',
      margin: 0,
      background: 'inherit',
      width: '100%',
      ...uischema?.config?.style?.componentsBoxStyle,
     }}
    >
     {uischema?.elements?.map((uischemaItem, i) => {
      const schemaClone = _.cloneDeep(schema);
      if (ctx.core.data?.[path]?.[index]?.disableRow) {
       const keysArray = Object.keys(schemaClone.properties);
       keysArray.map((e) => {
        schemaClone.properties[e].disabled = true;
       });
      }
      return (
       <Grid
        key={`${path}-${i}`}
        size={{
         xs: uischemaItem?.config?.layout?.xs ?? 12,
         sm: uischemaItem?.config?.layout?.sm ?? 12,
         md: uischemaItem?.config?.layout?.md ?? 12,
         lg: uischemaItem?.config?.layout?.lg ?? 12,
        }}
       >
        <JsonFormsDispatch
         uischema={uischemaItem}
         schema={schemaClone}
         path={childPath}
         enabled={enabled}
         renderers={renderers}
         cells={cells}
        />
       </Grid>
      );
     })}
    </Grid>
   </AccordionDetails>
  </Accordion>
 );
};

export default ArrayLayoutRenderer;
