/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import { useGridApiRef } from '@mui/x-data-grid-pro';
import { AddCircleOutlineRounded, InfoOutlined, PauseCircleFilledRounded } from '@mui/icons-material';

import { DAY_OPTIONS, PERMISSION_OPTIONS, STATUS_OPTIONS } from '@/modules/designSystem/modules/constants';

import { getIAB } from '@/modules/@common/iab/helpers';
import { getImportsString, getPropsString, imageAvatarUrl } from '@/modules/designSystem/modules/helpers';
import { getHashFromString } from '@/mui/helpers';
import { createFlatTreeMap } from '@/mui/helpers/treeView';

import IabSelector from '@/modules/@common/iab/components/IabSelector/IabSelector';
import Playground from '@/modules/designSystem/modules/Playground/Playground';
import AvatarEdit from './components/Edit';
import Avatar from '../../../../mui/components/Avatar/Avatar';
import Chip from '../../../../mui/components/Chip/Chip';
import { Box, DataGridPro, IconButton, Stack, Tooltip } from '@/mui/components';

import fullNames from './internal/fullNamesList.json';

const rows = new Array(100).fill(0).map((n, index) => {
  const dateTime = new Date(index * 1000).getTime();

  const getItemArray = (array) => array[index % (array.length - 1)];
  const email = `${getItemArray(fullNames.firstName)}.${getItemArray(fullNames.lastName)}@gmail.com`;
  const staticHash = Math.abs(getHashFromString(email));

  return {
    id: `${index}`,
    desk: `D-${index}`,
    logo: imageAvatarUrl,
    iab: ['1', '2'],
    email,
    verified: staticHash % 5 === 0,
    status: getItemArray(STATUS_OPTIONS),
    day: getItemArray(DAY_OPTIONS),
    permissions: [getItemArray(PERMISSION_OPTIONS)],
    price: staticHash % 10000,
    dateTime,
    date: dateTime,
    time: dateTime,
    rating: staticHash % 5,
    slider: Math.max(1, staticHash % 100),
    actions: null,
  };
});

const treeMapper = {
  label: 'name',
  children: 'categories',
};

function DataGridSection() {
  const [flatTree] = useState(createFlatTreeMap(getIAB(), treeMapper, []));
  const apiRef = useGridApiRef();

  const data$ = {
    initialState: {
      pagination: { paginationModel: { pageSize: 5, page: 0 } },
      columnVisibilityModel: {
        desk: false,
      },
    },
    columns: [
      {
        field: 'id',
        headerName: 'Id',
        width: 40,
      },
      {
        field: 'logo',
        headerName: 'custom cell',
        cellType: 'string',
        width: 80,
        editable: true,
        align: 'center',
        renderCellValue: (props) => <Avatar src={props.value} size={props.size} />,
        renderEditCell: (props) => <AvatarEdit {...props} />,
      },
      {
        field: 'iab',
        headerName: 'custom cell',
        cellType: 'multiSelect',
        width: 220,
        editable: true,
        renderCellValue: (props) =>
          !props.value.length ? (
            'No any tags'
          ) : (
            <Stack spacing={2} alignItems="center" direction="row" justifyContent="flex-start">
              {props.value.map((nodeId) => {
                const { label } = flatTree.get(nodeId);

                return <Chip key={nodeId} size={props.size} label={label} color="neutral" />;
              })}
            </Stack>
          ),
        renderEditCell: (props) => (
          <IabSelector
            {...props}
            autoFocus
            placeholder="Select IAB tag"
            value={props.value}
            size={props.size}
            onChange={(event, value) => {
              props.onChange(value.map(({ id }) => id));
            }}
          />
        ),
      },
      {
        field: 'email',
        headerName: 'cell (string)',
        cellType: 'string',
        width: 200,
        editable: true,
        renderHeader: (params) => (
          <Stack spacing={1} direction="row" alignItems="center">
            <div>{params.colDef.headerName}</div>
            <Tooltip title="This field is required for....">
              <InfoOutlined fontSize="small" htmlColor="info.main" />
            </Tooltip>
          </Stack>
        ),
        renderEditProps: () => ({
          root: {
            placeholder: 'Enter Email',
          },
        }),
      },
      {
        field: 'verified',
        headerName: 'cell (checkbox)',
        cellType: 'boolean',
        width: 100,
        editable: true,
      },
      {
        field: 'status',
        headerName: 'cell (singleSelect)',
        cellType: 'singleSelect',
        valueOptions: STATUS_OPTIONS,
        width: 180,
        editable: true,
      },
      {
        field: 'day',
        headerName: 'cell (autocompleteSelect)',
        cellType: 'autocompleteSelect',
        valueOptions: DAY_OPTIONS,
        width: 220,
        editable: true,
        renderEditProps: () => ({
          input: {
            placeholder: 'Select Day',
          },
        }),
      },
      {
        field: 'permissions',
        headerName: 'cell (multiSelect)',
        cellType: 'multiSelect',
        valueOptions: PERMISSION_OPTIONS,
        width: 250,
        editable: true,
        renderEditProps: () => ({
          input: {
            placeholder: 'Select Permission',
          },
        }),
      },
      {
        field: 'price',
        headerName: 'cell (number)',
        cellType: 'number',
        editable: true,
      },
      {
        field: 'dateTime',
        headerName: 'cell (dateTime)',
        cellType: 'dateTime',
        width: 200,
        editable: true,
      },
      {
        field: 'date',
        headerName: 'cell (date)',
        cellType: 'date',
        width: 120,
        editable: true,
      },
      {
        field: 'time',
        headerName: 'cell (time)',
        cellType: 'time',
        width: 100,
        editable: true,
      },
      {
        field: 'slider',
        headerName: 'cell (slider)',
        cellType: 'slider',
        width: 140,
        editable: true,
      },
      {
        field: 'rating',
        headerName: 'cell (rating)',
        cellType: 'rating',
        width: 150,
        editable: true,
        renderEditProps: () => ({
          root: {
            precision: 0.5,
          },
        }),
      },
      {
        field: 'actions',
        headerName: 'cell (actions)',
        cellType: 'actions',
        renderCellValue: (props) => (
          <>
            <IconButton size={props.size} color="success" title="Create" onClick={() => null}>
              <AddCircleOutlineRounded />
            </IconButton>
            <IconButton size={props.size} color="warning" title="Pause" onClick={() => null}>
              <PauseCircleFilledRounded />
            </IconButton>
          </>
        ),
      },
    ].filter(Boolean),
    rows,
  };

  return (
    <Playground
      title="DataGrid"
      fullWidth
      initialState={[
        {
          type: 'select',
          stateId: 'size',
          options: ['small', 'large'],
          selected: 'large',
        },
        {
          type: 'checkbox',
          stateId: 'pagination',
          selected: true,
        },
      ]}
      renderCallback={(state) => {
        const props = {
          ...state,
          apiRef,
          loading: data$.rows.length === 0,
          checkboxSelection: true,
          disableRowSelectionOnClick: true,
          initialState: data$.initialState,
          columns: data$.columns,
          rows: data$.rows,
          pageSizeOptions: [10, 15, 25],
        };

        const propsString = getPropsString({
          ...props,
          apiRef: '!!!apiRef',
        });
        const importsList = getImportsString([[['DataGridPro']]]);

        return {
          component: (
            <Box sx={{ height: 36 * 10, width: '100%' }}>
              <DataGridPro {...props} />
            </Box>
          ),
          code: `${importsList}
const apiRef = useGridApiRef();

<DataGridPro${propsString}/>`,
        };
      }}
    />
  );
}

export default DataGridSection;
