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 Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';

import { DashboardContent } from 'src/layouts/dashboard';
import docService, { Doc } from 'src/services/document-service';
import { Attribute, getAttributes } from 'src/services/attribute-service';

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

import { DocItem } from '../doc-item';
import { BoolFilter } from '../bool-filter';
import { TextFilter } from '../text-filter';
import CreateFilterModal from './create-filter-modal';
import { DecimalFilter, IntFilter } from '../num-filter';
import { DateFilter, DateTimeFilter, TimeFilter } from '../date-filter';
// ----------------------------------------------------------------------

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

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

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

  useEffect(() => {
    getAttributes().then((res) => {
      setFilters(res);
    });
  }, []);

  const [openCreateFilterModal, setOpenCreateFilterModal] = useState(false);

  const [docs, setDocs] = useState<Doc[]>([]);

  useEffect(() => {
    docService.get({}).then((res) => {
      setDocs(res);
    });
  }, []);

  //#region attributes
  const [attributes, setAttributes] = useState<Record<string, string>>({});

  useEffect(() => {
    docService.getByAttribute(attributes).then(setDocs);
  }, [attributes]);

  function setAttribute(name: string, serilizedValue: string) {
    setAttributes(prev => ({
      ...prev,
      [name]: serilizedValue
    }));
  }

  function removeAttribute(name: string) {
    setAttributes(prev => {
      const { [name]: _, ...rest } = prev;
      return rest;
    });
  }

  function updateAttribute(name: string, serilizedValue?: string | null) {
    if (serilizedValue)
      setAttribute(name, serilizedValue);
    else
      removeAttribute(name);
  }
  //#endregion

  //#region example components
  // <Box
  //   sx={{
  //     mb: 5,
  //     display: 'flex',
  //     alignItems: 'center',
  //     justifyContent: 'space-between',
  //   }}
  // >
  //   <DocSearch docs={docs} />
  //   <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" />}
          onClick={() => setOpenCreateFilterModal(true)}
          loading={openCreateFilterModal}
        >
          New filter
        </Button>
      </Box>

      <CreateFilterModal open={openCreateFilterModal} handleClose={() => setOpenCreateFilterModal(false)} />

      <Grid container spacing={3}>
        {filters.map((filter, index) => {

          let filterComp;
          switch (filter.type) {
            case 'BOOLEAN':
              filterComp = <BoolFilter label={filter.label ?? filter.name} />
              break;
            case 'INTEGER':
              filterComp = <IntFilter label={filter.label ?? filter.name} onChange={value => updateAttribute(filter.name, value)} />
              break;
            case 'DECIMAL':
              filterComp = <DecimalFilter label={filter.label ?? filter.name} onChange={value => updateAttribute(filter.name, value)} />
              break;
            case 'VARCHAR':
              filterComp = <TextFilter label={filter.label ?? filter.name} onChange={value => updateAttribute(filter.name, value)} />
              break;
            case 'DATE':
              filterComp = <DateFilter label={filter.label ?? filter.name} />
              break;
            case 'TIME':
              filterComp = <TimeFilter label={filter.label ?? filter.name} />
              break;
            case 'DATETIME':
              filterComp = <DateTimeFilter label={filter.label ?? filter.name} />
              break;
            default:
              console.error(`Unknown filter type: ${filter.type}`);
          }

          return (
            <Grid
              key={filter.id}
              size={{
                xs: 12,
                sm: 6,
                md: 3,
              }}
            >
              <Box
                sx={{
                  mb: 5,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                {filterComp}
              </Box>
            </Grid>
          );
        }
        )}
      </Grid>

      <Grid container spacing={3}>
        {docs.map((doc, index) => {
          const large = false;
          const long = false;

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

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