import { useState, useCallback, useEffect } from 'react';

import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import Switch from '@mui/material/Switch';
import Checkbox from '@mui/material/Checkbox';
import FormGroup from '@mui/material/FormGroup';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import AddBoxIcon from '@mui/icons-material/AddBox';
import FormControlLabel from '@mui/material/FormControlLabel';
import AddBoxTwoToneIcon from '@mui/icons-material/AddBoxTwoTone';

import { DashboardContent } from 'src/layouts/dashboard';
import { Filter, getFiltersAsync } from 'src/api/filter-service';

import { Iconify } from 'src/components/iconify';

import { DocItem } from '../doc-item';

import type { IDocItem } from '../doc-item';
// ----------------------------------------------------------------------

type Props = {
  posts: IDocItem[];
};

export function DocSearchView({ posts }: Props) {
  const [sortBy, setSortBy] = useState('latest');

  const [filters, setFilters] = useState<Filter[]>([])

  const [disabledStates, setDisabledStates] = useState<Record<number, boolean>>({});

  const setDisabledState = useCallback((index: number, state: boolean) => {
    setDisabledStates(prev => ({
      ...prev,
      [index]: state,
    }));
  }, []);

  const handleSort = useCallback((newSort: string) => {
    setSortBy(newSort);
  }, []);

  useEffect(() => {
    getFiltersAsync().then((res) => {
      setFilters(res);
      const newDisabledStates = res.reduce<Record<number, boolean>>((acc, filter, index) => {
        if (filter.type === 'BOOLEAN') {
          acc[index] = true;
        }
        return acc;
      }, {});
      setDisabledStates(newDisabledStates);
    });
  }, []);

  //#region example components
  // <Box
  //   sx={{
  //     mb: 5,
  //     display: 'flex',
  //     alignItems: 'center',
  //     justifyContent: 'space-between',
  //   }}
  // >
  //   <DocSearch posts={posts} />
  //   <DocSort
  //     sortBy={sortBy}
  //     onSort={handleSort}
  //     options={[
  //       { value: 'latest', label: 'Latest' },
  //       { value: 'popular', label: 'Popular' },
  //       { value: 'oldest', label: 'Oldest' },
  //     ]}
  //   />
  // </Box>
  //#endregion

  return (
    <DashboardContent>

      <Box
        sx={{
          mb: 5,
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <Typography variant="h4" sx={{ flexGrow: 1 }}>
          Document Search
        </Typography>
        <Button
          variant="contained"
          color="inherit"
          startIcon={<Iconify icon="mingcute:add-line" />}
        >
          New filter
        </Button>
      </Box>

      <>
        {filters.map((filter, index) => {
          let filterComp;
          switch (filter.type) {
            case 'BOOLEAN':
              filterComp =
                <FormGroup row>
                  <Checkbox
                    {...{ inputProps: { 'aria-label': 'Checkbox demo' } }}
                    icon={<AddBoxTwoToneIcon />}
                    checkedIcon={<AddBoxIcon />}
                    onClick={() => setDisabledState(index, !disabledStates[index])}
                  />
                  {
                    disabledStates[index] === undefined || disabledStates[index]
                      ? <FormControlLabel disabled control={<Switch />} label={filter.label ?? filter.name} />
                      : <FormControlLabel control={<Switch />} label={filter.label ?? filter.name} />
                  }
                </FormGroup>
              break;
            case 'VARCHAR':
            case 'INTEGER':
            case 'DECIMAL':
            case 'DATE':
            default:
              filterComp = (<TextField id={`filter-${filter.id.toString()}`} label={filter.label ?? filter.type} variant="filled" />)
              break;
          }
          return (
            <Box
              sx={{
                mb: 5,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
            >
              {filterComp}
            </Box>
          )
        }
        )}
      </>

      <Grid container spacing={3}>
        {posts.map((post, index) => {
          const latestDocLarge = index === 0;
          const latestDoc = index === 1 || index === 2;

          return (
            <Grid
              key={post.id}
              size={{
                xs: 12,
                sm: latestDocLarge ? 12 : 6,
                md: latestDocLarge ? 6 : 3,
              }}
            >
              <DocItem post={post} latestDoc={latestDoc} latestDocLarge={latestDocLarge} />
            </Grid>
          );
        })}
      </Grid>

      <Pagination count={10} color="primary" sx={{ mt: 8, mx: 'auto' }} />
    </DashboardContent>
  );
}
