import React, { useState } from 'react';
import { AddRounded, CheckRounded, CloseRounded } from '@mui/icons-material';

import { SORT_ASC, SORT_DESC } from '@/modules/@common/constants/sort';
import { DAY_OPTIONS, PERMISSION_OPTIONS, STATUS_OPTIONS } from '@/modules/designSystem/modules/constants';

import { getOptions } from '@/modules/designSystem/modules/helpers';

import {
  Form,
  FormContent,
  FormGroup,
  FormGroupTitle,
  FormImageUploader,
  FormRow,
  FormRowItem,
  FormSection,
} from '@/modules/@common/Form';
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Autocomplete,
  Button,
  Checkbox,
  FormControlLabel,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  TableScroll,
  TableSortLabel,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Typography,
} from '@/mui/components';

import fullNames from '@/modules/designSystem/modules/DataGridSection/internal/fullNamesList.json';

import styles from './FormsSection.module.scss';

const options = getOptions(20);

//todo: create code sample on view
const rows = new Array(105).fill(0).map((n, index) => {
  const getItemArray = (array) => array[index % (array.length - 1)];

  return {
    id: index + 1,
    desk: `D-${index}`,
    email: `${getItemArray(fullNames.firstName)}.${getItemArray(fullNames.lastName)}@gmail.com`,
    verified: index % 5 === 0,
    status: getItemArray(STATUS_OPTIONS),
    permissions: [getItemArray(PERMISSION_OPTIONS)],
    day: getItemArray(DAY_OPTIONS),
  };
});

function descendingComparator(a, b, orderBy) {
  if (b[orderBy] < a[orderBy]) {
    return -1;
  }
  if (b[orderBy] > a[orderBy]) {
    return 1;
  }
  return 0;
}

function getComparator(order, orderBy) {
  return order === SORT_DESC
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy);
}

const headCells = [
  {
    id: 'id',
    headerName: 'Id',
  },
  {
    id: 'email',
    headerName: 'Email',
  },
  {
    id: 'verified',
    align: 'center',
    headerName: 'Verified',
  },
  {
    id: 'status',
    headerName: 'Status',
  },
  {
    id: 'day',
    headerName: 'Day',
  },
  {
    id: 'permissions',
    headerName: 'Permissions',
  },
];

function FormsSection() {
  const [countOfForms, setCount] = useState(2);
  const [order, setOrder] = useState(SORT_ASC);
  const [orderBy, setOrderBy] = useState('id');
  const [selected, setSelected] = useState([]);
  const [page, setPage] = useState(1);
  const [rowsPerPageOptions] = useState([10, 15, 25]);
  const [rowsPerPage, setRowsPerPage] = useState(rowsPerPageOptions[0]);

  const indexStart = (page - 1) * rowsPerPage;
  const indexEnd = indexStart + rowsPerPage;

  const formSize = 'small';

  return (
    <>
      <div>
        <ToggleButtonGroup
          exclusive
          value={countOfForms}
          color="primary"
          onChange={(event, newState) => {
            if (newState) {
              setCount(newState);
            }
          }}
        >
          <ToggleButton value={1}>1 Form Section</ToggleButton>
          <ToggleButton value={2}>2 Form Sections</ToggleButton>
        </ToggleButtonGroup>
      </div>
      <div className={styles.CompareWrapper}>
        <Form>
          <FormContent>
            {new Array(countOfForms)
              .fill(0)
              .map((_, index) => index + 1)
              .map((num) => (
                <FormSection key={num} size={formSize}>
                  <FormGroupTitle>{`Primary ${num}`}</FormGroupTitle>
                  <FormRow label="Sub items" tooltip="Chose where to display the list of chips">
                    {new Array(4)
                      .fill(0)
                      .map((_, index) => `${index}`)
                      .map((key) => (
                        <TextField key={key} size={formSize} value={key} />
                      ))}
                  </FormRow>
                  <FormRow label="Sub items" tooltip="Chose where to display the list of chips">
                    <FormRowItem itemsInRow={2}>
                      <TextField size={formSize} />
                    </FormRowItem>
                    <TextField size={formSize} />
                  </FormRow>
                  <FormRow label="Single Info Icon" tooltip="Chose where to display the list of chips" fullWidth>
                    <TextField size={formSize} value="100%" />
                    <Button size={formSize}>Validate email</Button>
                    <Switch checked size={formSize} />
                  </FormRow>
                  <FormGroupTitle>Some random title</FormGroupTitle>
                  <FormRow label="Upload" tooltip="Upload tooltip" fullWidth>
                    <FormImageUploader
                      image={null}
                      accept="image/*"
                      onValidate={
                        (/*file*/) =>
                          // console.log(file);
                          // 250 * 1000
                          true
                      }
                      onLoad={() => null}
                      onError={() => null}
                      restrictionMessage={'JPEG, PNG, SVG.\n Maximum allowed file size for image is 5mb.'}
                    />
                  </FormRow>
                  <FormRow label="Accordion" tooltip="Chose where to display the list of chips" />
                  <FormRow fullWidth>
                    <Stack spacing={0} fullWidth>
                      <Accordion>
                        <AccordionSummary>
                          <Typography>Accordion 1</Typography>
                        </AccordionSummary>
                        <AccordionDetails className={styles.AccordionDetails}>
                          <Stack spacing={2}>
                            <FormControlLabel
                              control={<Switch defaultChecked onChange={() => null} />}
                              label="Slides"
                            />
                            <FormControlLabel
                              control={<Switch defaultChecked onChange={() => null} />}
                              label="Transcript"
                            />
                            <FormControlLabel
                              control={<Switch defaultChecked onChange={() => null} />}
                              label="Highlights"
                            />
                          </Stack>
                        </AccordionDetails>
                      </Accordion>
                      <Accordion fullWidth defaultExpanded>
                        <AccordionSummary>
                          <Typography>Accordion 2</Typography>
                        </AccordionSummary>
                        <AccordionDetails className={styles.AccordionDetails}>
                          <Typography component="div" variant="body2" color="text.secondary">
                            In the vast expanse of the universe lies a galaxy teeming with mysteries and wonders.
                            Spirals of stars, dust, and gas swirl in a cosmic dance, forming brilliant clusters and
                            nebulae. Within this galaxy, billions of stars illuminate the darkness, each potentially
                            hosting planetary systems with unknown worlds. The Milky Way, our galactic home, stretches
                            across the night sky, its dense core hiding supermassive black holes. As we explore, we
                            uncover the secrets of stellar nurseries, ancient supernovae, and the ever-expanding
                            universe.
                          </Typography>
                        </AccordionDetails>
                      </Accordion>
                    </Stack>
                  </FormRow>
                  <FormGroupTitle>Other changes</FormGroupTitle>
                  <FormRow label="Change device type" fullWidth>
                    <ToggleButtonGroup equalWidth size={formSize} value="0" color="primary">
                      {new Array(2)
                        .fill(0)
                        .map((_, index) => `${index}`)
                        .map((key) => (
                          <ToggleButton key={key} value={key}>
                            {key}
                          </ToggleButton>
                        ))}
                    </ToggleButtonGroup>
                  </FormRow>
                  <FormRow label="Toggle Button Group" fullWidth />
                  <FormRow fullWidth>
                    <ToggleButtonGroup equalWidth size={formSize} value="0" color="primary">
                      {new Array(16)
                        .fill(0)
                        .map((_, index) => `${index}`)
                        .map((key) => (
                          <ToggleButton key={key} value={key}>
                            {key}
                          </ToggleButton>
                        ))}
                    </ToggleButtonGroup>
                  </FormRow>
                  <FormRow
                    fullWidth
                    label="Two Line Text with an Info Icon 3 line example"
                    tooltip="Chose where to display the list of chips"
                  >
                    <FormRowItem itemsInRow={4}>
                      <TextField size={formSize} value="" />
                    </FormRowItem>
                    <TextField size={formSize} value="" />
                  </FormRow>
                  <FormRow label="Mixed 1" multiline>
                    <FormRowItem itemsInRow={2}>
                      <TextField size={formSize} defaultValue="" />
                    </FormRowItem>
                    <FormRowItem itemsInRow={2}>
                      <TextField size={formSize} defaultValue="" />
                    </FormRowItem>
                    <FormRowItem component={Typography} variant="body2" itemsInRow={2}>
                      Aspect Ratio
                    </FormRowItem>
                    <FormRowItem itemsInRow={2}>
                      <TextField size={formSize} value="16x9" />
                    </FormRowItem>
                  </FormRow>
                  <FormRow
                    label="Autocomplete Multiple Rows ( Needs update )"
                    tooltip="Chose where to display the list of chips"
                    fullWidth
                  >
                    <Autocomplete
                      size={formSize}
                      defaultValue={options.slice(0, 2)}
                      multiple
                      optionLabelKey="label"
                      optionValueKey="value"
                      options={options}
                      renderInput={(params$) => <TextField {...params$} size={formSize} variant="outlined" />}
                    />
                  </FormRow>
                  <FormRow
                    label="Table in Row"
                    tooltip="Chose where to display the list of chips"
                    fullWidth
                    justifyContent="flex-end"
                  >
                    <Button size={formSize} color="neutral" variant="text">
                      Schedule message
                    </Button>
                    <Button startIcon={<AddRounded />} size={formSize} color="primary" variant="contained">
                      Add Session
                    </Button>
                  </FormRow>
                  <FormRow fullWidth>
                    <TableContainer>
                      <TableScroll>
                        <Table size={formSize}>
                          <TableHead>
                            <TableRow>
                              <TableCell padding="checkbox" align="center">
                                <Checkbox
                                  color="primary"
                                  indeterminate={selected.length > 0 && selected.length < rows.length}
                                  checked={rows.length > 0 && selected.length === rows.length}
                                  onChange={(event) => {
                                    setSelected(event.target.checked ? rows.map((n) => n.id) : []);
                                  }}
                                  inputProps={{
                                    'aria-label': 'select all desserts',
                                  }}
                                />
                              </TableCell>
                              {headCells.map((headCell) => (
                                <TableCell
                                  key={headCell.id}
                                  align={headCell.align}
                                  padding={headCell.padding}
                                  sortDirection={orderBy === headCell.id ? order : false}
                                >
                                  <TableSortLabel
                                    active={orderBy === headCell.id}
                                    direction={orderBy === headCell.id ? order : SORT_ASC}
                                    onClick={() => {
                                      const isAsc = orderBy === headCell.id && order === SORT_ASC;
                                      setOrder(isAsc ? SORT_DESC : SORT_ASC);
                                      setOrderBy(headCell.id);
                                    }}
                                  >
                                    {headCell.headerName}
                                  </TableSortLabel>
                                </TableCell>
                              ))}
                            </TableRow>
                          </TableHead>
                          <TableBody>
                            {rows
                              .sort(getComparator(order, orderBy))
                              .slice(indexStart, indexEnd)
                              .map((row) => {
                                const isItemSelected = selected.includes(row.id);

                                return (
                                  <TableRow
                                    key={row.id}
                                    hover
                                    role="checkbox"
                                    aria-checked={isItemSelected}
                                    selected={isItemSelected}
                                  >
                                    <TableCell padding="checkbox" align="center">
                                      <Checkbox color="primary" checked={isItemSelected} />
                                    </TableCell>
                                    <TableCell>{row.id}</TableCell>
                                    <TableCell noWrap>
                                      <div className={styles.NoWrap}>{row.email}</div>
                                    </TableCell>
                                    <TableCell align="center">
                                      {row.verified ? <CheckRounded /> : <CloseRounded />}
                                    </TableCell>
                                    <TableCell noWrap>{row.status}</TableCell>
                                    <TableCell>{row.day}</TableCell>
                                    <TableCell>{row.permissions.map(({ label }) => label).join(', ')}</TableCell>
                                  </TableRow>
                                );
                              })}
                          </TableBody>
                        </Table>
                      </TableScroll>
                      <TablePagination
                        size={formSize}
                        rowsPerPageOptions={rowsPerPageOptions}
                        component="div"
                        count={rows.length}
                        rowsPerPage={rowsPerPage}
                        page={page}
                        onPageChange={(event, newPage) => setPage(newPage)}
                        onRowsPerPageChange={(event) => {
                          setRowsPerPage(parseInt(event.target.value, 10));
                          setPage(1);
                        }}
                      />
                    </TableContainer>
                  </FormRow>
                  <FormGroup>
                    <FormRow label="Sub items" tooltip="Chose where to display the list of chips" multiline>
                      {new Array(4)
                        .fill(0)
                        .map((_, index) => `${index}`)
                        .map((key) => (
                          <FormRowItem key={key} itemsInRow={4}>
                            <TextField size={formSize} value={key} />
                          </FormRowItem>
                        ))}
                    </FormRow>
                    <FormRow label="Sub items" tooltip="Chose where to display the list of chips">
                      {new Array(4)
                        .fill(0)
                        .map((_, index) => `${index}`)
                        .map((key) => (
                          <TextField size={formSize} key={key} value={key} />
                        ))}
                    </FormRow>
                  </FormGroup>
                  <FormRow multiline>
                    <FormControlLabel
                      control={<Checkbox defaultChecked onChange={() => null} name="gilad" />}
                      label="Gilad Gray"
                    />
                    <FormControlLabel
                      control={<Checkbox defaultChecked={false} onChange={() => null} name="jason" />}
                      label="Jason Killian"
                    />
                    <FormControlLabel
                      control={<Checkbox defaultChecked={false} onChange={() => null} name="antoine" />}
                      label="Antoine Llorca"
                    />
                    <FormControlLabel
                      control={<Checkbox defaultChecked={false} onChange={() => null} name="robert" />}
                      label="Robert Smithson"
                    />
                  </FormRow>
                </FormSection>
              ))}
          </FormContent>
        </Form>
      </div>
    </>
  );
}

export default FormsSection;
