import * as React from 'react';
import { memo, useContext, useEffect, useState } from 'react';
import _ from 'lodash';
import {
  useJsonForms,
 withArrayTranslationProps,
 withJsonFormsArrayLayoutProps,
 withTranslateProps,
} from '@jsonforms/react';
import { DataContext } from '../../context/Context';
import { Box, styled } from '@mui/system';
import {
 Accordion,
 AccordionDetails,
 AccordionProps,
 AccordionSummary,
 AccordionSummaryProps,
 IconButton,
 Typography,
} from '@mui/material';
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
import Grid from '@mui/material/Grid2';
import ArrayLayout from './ArrayLayout';
import { ButtonIcon } from '../../common/ButtonIcon';
import { createDefaultValue } from '@jsonforms/core';

const StyledAccordion = styled((props: AccordionProps) => (
 <Accordion disableGutters elevation={0} square {...props} />
))(({ theme }) => ({
 border: `none`,
}));

const StyledAccordionSummary = styled((props: AccordionSummaryProps) => (
 <AccordionSummary expandIcon={<ArrowRightIcon />} {...props} />
))(({ theme }: any) => ({
 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 Array = function (props: any) {
 const {
  uischema,
  path,
  data,
  schema,
  enabled,
  renderers,
  rootSchema,
  cells,
  addItem,
  removeItems,
 } = props;
 //  console.log(schema)
 const [expanded, setExpanded] = React.useState<string | false>('panel');
 const { theme, handleToggleArray, arrayExpendState, serviceProvider } =
  useContext(DataContext);
 useEffect(() => {
  handleToggleArray(path, uischema.config?.main?.allExpanded ?? false);
 }, [uischema.config?.main?.allExpanded]);
 const ctx = useJsonForms();
 const dynamicStyle = React.useMemo(() => {
  return serviceProvider(
   ctx,
   {
    onClick: uischema.config?.main?.styleFunction || 'getStyle',
   },
   {
    event: { _reactName: 'onClick' },
    path,
   },
  );
 }, [data, path]);
 const componentStyle = { ...uischema.config?.style, ...dynamicStyle };
 const handleAccordionChange =
  () => (event: React.SyntheticEvent, newExpanded: boolean) => {
   setExpanded(newExpanded ? 'panel' : false);
  };

 const handleChildAccordionMaximize = () => {
  handleToggleArray(path, true);
 };

 const handleChildAccordionMinimize = () => {
  handleToggleArray(path, false);
 };

 const handleDelete = (index: number) => {
  removeItems(path, [index])();
 };
 return (
  <StyledAccordion
   key={path}
   expanded={expanded === 'panel'}
   onChange={handleAccordionChange()}
   sx={{
    ...uischema?.config?.style,
   }}
  >
   <StyledAccordionSummary
    aria-controls='panel-content'
    id={`panel-header-${path}`}
    sx={{
     padding: 0,
     borderBottom: `1px solid ${theme.myTheme.palette.grey[700]}40`,
     '& .MuiAccordionSummary-content': {
      margin: 0,
     },
     ...componentStyle?.accordionSummaryStyle,
    }}
   >
    {uischema?.config?.main?.label && (
     <Box>
      <Typography
       component={'div'}
       sx={{
        fontSize: {
         xs: theme.myTheme.typography.fontSize * 1.2,
         md: theme.myTheme.typography.fontSize * 1.5,
         lg: theme.myTheme.typography.fontSize * 1.6,
        },
        // fontFamily: "roboto",
        fontWeight: 'bold',
        color: 'inherit',
        marginLeft: '24px',
        ...uischema?.config?.style?.labelStyle,
       }}
      >
       {uischema.config?.main?.label}
      </Typography>
     </Box>
    )}
   </StyledAccordionSummary>

   <AccordionDetails
    sx={{ paddingBottom: '12px', ...uischema?.config?.style?.detailsStyle }}
   >
    <Grid
     sx={{
      display: 'flex',
      flexDirection: 'row',
      paddingLeft: '0',
      justifyContent: 'space-between',
      alignItems: 'center',
     }}
    >
     <Grid>{data.length === 0 && 'No data'}</Grid>
     <Grid sx={{ display: 'flex', flexDirection: 'row' }}>
      {!uischema?.config?.main?.disableAddButton && (
       <Grid
        onClick={addItem(path, createDefaultValue(schema, rootSchema))}
        sx={{
         textAlign: 'center',
         padding: '8px 4px 4px',
         color: theme.myTheme.palette.common.black,
         fill: theme.myTheme.palette.common.black,
         display: 'flex',
         flexDirection: 'column',
         justifyContent: 'center',
         '&:hover': {
          color: theme.myTheme.palette.primary.main,
          fill: theme.myTheme.palette.primary.main,
         },
         ...uischema.config.style?.addButtontyle,
        }}
       >
        {' '}
        <IconButton
         disableRipple
         sx={{ color: theme.myTheme.palette.common.black }}
        >
         {ButtonIcon('TableAddIcon', {})}
        </IconButton>
        <Typography
         sx={{
          fontSize: '9px',
          color: 'inherit',
          display: 'block',
         }}
        >
         Add
        </Typography>
       </Grid>
      )}

      {!uischema?.config?.main?.disableExpandAllButton && (
       <>
        <Grid
         key={`Maximize-${path}`}
         onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          handleChildAccordionMaximize();
         }}
         sx={{
          textAlign: 'center',
          padding: '8px 4px 4px',
          color:
           data.length === 0
            ? `${theme.myTheme.palette.common.black}80`
            : theme.myTheme.palette.common.black,
          fill:
           data.length === 0
            ? `${theme.myTheme.palette.common.black}80`
            : theme.myTheme.palette.common.black,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          '&:hover': {
           color:
            data.length === 0
             ? `${theme.myTheme.palette.common.black}80`
             : theme.myTheme.palette.primary.main,
           fill:
            data.length === 0
             ? `${theme.myTheme.palette.common.black}80`
             : theme.myTheme.palette.primary.main,
           ...uischema.config.style?.ExpandAllButtontyle,
          },
         }}
        >
         {' '}
         <IconButton disableRipple disabled={data.length === 0}>
          {ButtonIcon('Maximize', {})}
         </IconButton>
         <Typography
          sx={{
           fontSize: '9px',
           color: 'inherit',
           display: 'block',
          }}
         >
          Maximise All
         </Typography>
        </Grid>
        <Grid
         key={`Minimize-${path}`}
         onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          handleChildAccordionMinimize();
         }}
         sx={{
          textAlign: 'center',
          padding: '8px 4px 4px',
          color:
           data.length === 0
            ? `${theme.myTheme.palette.common.black}80`
            : theme.myTheme.palette.common.black,
          fill:
           data.length === 0
            ? `${theme.myTheme.palette.common.black}80`
            : theme.myTheme.palette.common.black,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          '&:hover': {
           color:
            data.length === 0
             ? `${theme.myTheme.palette.common.black}80`
             : theme.myTheme.palette.primary.main,
           fill:
            data.length === 0
             ? `${theme.myTheme.palette.common.black}80`
             : theme.myTheme.palette.primary.main,
          },
         }}
        >
         <IconButton disableRipple disabled={data.length === 0}>
          {ButtonIcon('Minimize', {})}
         </IconButton>
         <Typography
          sx={{
           fontSize: '9px',
           color: 'inherit',
           display: 'block',
          }}
         >
          Minimise All
         </Typography>
        </Grid>
       </>
      )}
     </Grid>
    </Grid>
    <Box>
     {_.range(data)?.map((item: any, index: number) => {
      return (
       <ArrayLayout
        componentStyle={componentStyle}
        key={index}
        uischema={uischema}
        schema={schema}
        path={path}
        renderers={renderers}
        enabled={enabled}
        cells={cells}
        index={index}
        theme={theme}
        handleDelete={handleDelete}
        arrayExpendState={arrayExpendState}
       />
      );
     })}
    </Box>
   </AccordionDetails>
  </StyledAccordion>
 );
};

export default withJsonFormsArrayLayoutProps(
 withTranslateProps(withArrayTranslationProps(Array)),
);
