import React, { useContext } from 'react';
import { Box, Grid2, Stack, Typography } from '@mui/material';
import AvatarFrame from '../assets/AvatarFrame';
import AvatarFrameMain from '../assets/AvatarFrameMain';
import { getComponentProps } from '../common/getComponentProps';
import { inputProps } from '../interface/inputfieldProps';
import { DataContext } from '../context/Context';
import { JsonFormsDispatch, useJsonForms, withJsonFormsControlProps } from '@jsonforms/react';
import { getFieldName } from '../permissions/getFieldName';
import ComponentWrapper from '../common/ComponentWrapper';
import defaultImage from '../assets/DefaultImage.png';
import { toLocaleStringForAmount } from '../common/formatUtils';

const LeaderBoard = React.memo(
 ({ data, uischema, path, schema, rootSchema, renderers }: inputProps) => {
  const uischemaData = uischema.config.main;
  const { pageName, permissions, theme, locale,serviceProvider} = useContext(DataContext);
  const fieldName = getFieldName(path);
  const nameKey = uischemaData.nameKey ?? 'name';
  const imageKey = uischemaData.imageKey ?? 'image';
  const scoreKey = uischemaData.scoreKey ?? 'score';
  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 getScoreValue = (value: string | number) => {
   if (value === null || value === undefined) return '';
   return uischemaData.isScoreAmount
    ? toLocaleStringForAmount(value, locale)
    : value;
  };

  const tableUiSchema = {
   type: 'Control',
   scope: path,
   options: {
    widget: 'Table',
   },
   config: {
    main: {
     enableTopToolbar: false,
     enableBottomToolbar: false,
     disableSorting: true,
     disableColumnResizing: true,
     disablePagination: true,
     initialDensity: 'comfortable',
     isLeaderBoard: true,
    },
    style: {
     height: '100%',
     border: 'none',
     borderRadius: '8px',
     tableBodystyle: {
      '& tr:nth-of-type(1)': {
       backgroundColor: '#E3B505 !important',
       '& td': {
        color: 'white',
       },
      },
      '& tr:nth-of-type(2)': {
       backgroundColor: `${theme.myTheme.palette.primary.main} !important`,
       '& td': {
        color: 'white',
       },
      },
      '& tr:nth-of-type(3)': {
       backgroundColor: `${theme.myTheme.palette.primary.main} !important`,
       '& td': {
        color: 'white',
       },
      },
      '& tr:not(:nth-child(-n+3))': {
       '& td': {
        borderRight: '1px solid #c6c6c6',
       },
      },
      '& tr:nth-of-type(1): hover': {
       backgroundColor: '#E3B505 !important',
      },
      '& tr:nth-of-type(2): hover': {
       backgroundColor: `${theme.myTheme.palette.primary.main} !important`,
       '& td': {
        color: 'white',
       },
      },
      '& tr:hover': {
       '& td:after': {
        backgroundColor: 'transparent',
       },
      },
      '& tr': {
       '& td': {
        fontWeight: 'bold',
        paddingTop: '0px',
        paddingBottom: '0px',
        '& div': {
         fontSize: '12px !important',
        },
       },
      },
     },
     tableHeadstyle: {
      background: theme.myTheme.palette.grey[700],
      color: 'white',
      boxShadow: 'none',
      fontWeight: 'bold',
     },
     tablePaperstyle: {
      height: '100%',
      border: 'none',
      borderRadius: '8px',
     },
     tableContainerstyle: {
      height: '100%',
      '&': {
       scrollbarGutter: 'stable',
       overflow: 'overlay',
      },
      '&::-webkit-scrollbar': {
       width: '7px',
       height: '7px',
      },
      '&::-webkit-scrollbar-track': {
       background: 'transparent',
      },
      '&::-webkit-scrollbar-thumb': {
       background: '#b1b1b1',
      },
      '&::-webkit-scrollbar-thumb:hover': {
       background: '#808080',
      },
     },
    },
   },
   elements: uischema.elements ?? [],
  };

  return (
   <ComponentWrapper
    {...getComponentProps(
     `${pageName}:${fieldName}`,
     permissions,
     schema,
     rootSchema,
    )}
   >
    <Grid2
     container
     alignItems={{
      xs: 'start',
      md: 'center',
     }}
     gap={2}
     sx={{
      flexDirection: {
       xs: 'column-reverse',
       md: 'row',
      },
      flexWrap: 'nowrap',
      width: '100%',
      height: {
       xs: '550px',
       md: '300px',
      },
      ...componentStyle,
     }}
    >
     <Grid2
      size={{
       xs: 12,
       md: 7,
      }}
      sx={{
       height: {
        xs: '50%',
        md: '100%',
       },
       ...componentStyle.tableContainerStyle,
      }}
     >
      <JsonFormsDispatch
       schema={schema}
       uischema={tableUiSchema}
       path={path}
       key={path + 'table'}
       renderers={renderers}
      />
     </Grid2>

     <Grid2
      size={{
       xs: 12,
       md: 5,
      }}
      sx={{
       display: 'flex',
       alignItems: 'center',
       height: {
        xs: '50%',
        md: '100%',
       },
       maxHeight: {
        xs: '270px',
        md: 'inherit',
       },
       position: 'relative',
       ...componentStyle.rankContainerStyle,
      }}
     >
      <Box
       sx={{
        position: 'relative',
        textAlign: 'center',
        width: '33%',
        height: '100%',
       }}
      >
       <AvatarFrame
        width='105%'
        height='70%'
        rank={2}
        name={data?.[1]?.[nameKey] || ''}
        image={
         data?.[1]?.[imageKey] || uischemaData?.secondImage || defaultImage
        }
        imageWidth={
         data?.[1]?.[imageKey] || uischemaData?.firstImage ? '100%' : '90%'
        }
        theme={theme.myTheme}
        sx={{
         position: 'absolute',
         left: '50%',
         top: '50%',
         transform: 'translate(-50%, -50%)',
         maxWidth: '190px',
         ...componentStyle.secondPlaceStyle,
        }}
       />
       <Typography
        sx={{
         position: 'absolute',
         bottom: { xs: '30%', sm: '14%', md: '36%', lg: '22%' },
         width: '100%',
         fontSize: { xs: '11px', md: '11px', sm: '18px', lg: '18px' },
         fontWeight: 'bolder',
        }}
       >
        {getScoreValue(data?.[1]?.[scoreKey])}
       </Typography>
      </Box>
      <Box
       sx={{
        position: 'relative',
        textAlign: 'center',
        width: '33%',
        height: '100%',
       }}
      >
       <AvatarFrameMain
        width='130%'
        height='100%'
        rank={1}
        name={data?.[0]?.[nameKey] || ''}
        image={
         data?.[0]?.[imageKey] || uischemaData?.firstImage || defaultImage
        }
        imageWidth={
         data?.[0]?.[imageKey] || uischemaData?.firstImage ? '100%' : '95%'
        }
        sx={{
         position: 'absolute',
         left: '50%',
         top: '50%',
         transform: 'translate(-50%, -50%)',
         zIndex: 1,
         maxWidth: '240px',
         ...componentStyle.firstPlaceStyle,
        }}
       />
       <Typography
        sx={{
         position: 'absolute',
         bottom: { xs: '27%', sm: '5%', md: '32%', lg: '15%' },
         width: '100%',
         fontSize: { xs: '11px', md: '12px', sm: '18px', lg: '20px' },
         fontWeight: 'bolder',
        }}
       >
        {getScoreValue(data?.[0]?.[scoreKey])}
       </Typography>
      </Box>
      <Box
       sx={{
        position: 'relative',
        textAlign: 'center',
        width: '33%',
        height: '100%',
       }}
      >
       <AvatarFrame
        width='105%'
        height='70%'
        rank={3}
        name={data?.[2]?.[nameKey] || ''}
        image={
         data?.[2]?.[imageKey] || uischemaData?.thirdImage || defaultImage
        }
        imageWidth={
         data?.[2]?.[imageKey] || uischemaData?.firstImage ? '100%' : '90%'
        }
        theme={theme.myTheme}
        sx={{
         position: 'absolute',
         left: '50%',
         top: '50%',
         transform: 'translate(-50%, -50%)',
         maxWidth: '200px',
         ...componentStyle.thirdPlaceStyle,
        }}
       />
       <Typography
        sx={{
         position: 'absolute',
         bottom: { xs: '30%', sm: '12%', md: '36%', lg: '21%' },
         width: '100%',
         fontSize: { xs: '11px', md: '11px', sm: '18px', lg: '18px' },
         fontWeight: 'bolder',
        }}
       >
        {getScoreValue(data?.[2]?.[scoreKey])}
       </Typography>
      </Box>
     </Grid2>
    </Grid2>
   </ComponentWrapper>
  );
 },
);

export default withJsonFormsControlProps(LeaderBoard);
