import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { SearchRounded } from '@mui/icons-material';

import { SEARCH_TEXT_MAX_LENGTH, TEMPLATE_CATEGORY_ALL } from '@/modules/forms/constants';
import { GET_TEMPLATE_STATUS_INITIAL } from '@/modules/forms/forms/constants';

import { getTemplateGalleryAction, getTemplateGalleryCategoryAction, setFieldAction } from '../../redux/slices';
import { getTemplates } from '@/modules/forms/forms/helpers/calculationsFromState';
import { setTemplateId } from '@/modules/forms/forms/helpers/upsertLastUsedTemplates';
import * as formsSelector from '@/modules/forms/forms/redux/selectors';

import TemplateItem from './components/TemplateItem';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  InputAdornment,
  MenuItem,
  Select,
  Stack,
  TextField,
  Typography,
} from '@/mui/components';

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

function TemplateGallery(props) {
  const router = useRouter();
  const dispatch = useDispatch();
  const templates = useSelector((state) => getTemplates(state));
  const lastUsedTemplates = useSelector(formsSelector.lastUsedTemplatesSelector);
  const templateSearchText = useSelector(formsSelector.templateSearchTextSelector);
  const templateCategory = useSelector(formsSelector.templateCategorySelector);
  const templateCategoryOptions = useSelector(formsSelector.templateCategoryOptionsSelector);

  const handleSearch = (searchText) => {
    dispatch(setFieldAction({ templateSearchText: searchText }));
    dispatch(getTemplateGalleryAction());
  };

  const handleChangeCategory = (category) => {
    dispatch(setFieldAction({ templateCategory: category }));
    dispatch(getTemplateGalleryAction());
  };

  const handleClose = () => {
    dispatch(
      setFieldAction({
        templateSearchText: '',
        templateCategory: TEMPLATE_CATEGORY_ALL,
      }),
    );
    props.onClose();
  };

  useEffect(() => {
    if (props.isOpen) {
      dispatch(getTemplateGalleryCategoryAction());
      dispatch(getTemplateGalleryAction(GET_TEMPLATE_STATUS_INITIAL));
    }
  }, [props.isOpen]);

  return (
    <Dialog
      open={props.isOpen}
      onClose={handleClose}
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      maxWidth="xl"
    >
      <DialogTitle onClose={handleClose}>Select Template</DialogTitle>
      <DialogContent className={styles.DialogContent}>
        <Stack direction="row" spacing={2}>
          <Select size="small" value={templateCategory} onChange={({ target }) => handleChangeCategory(target.value)}>
            {templateCategoryOptions.map((status) => (
              <MenuItem value={status.value} key={status.value}>
                {status.label}
              </MenuItem>
            ))}
          </Select>
          <TextField
            id="search"
            value={templateSearchText}
            onChange={({ target }) => handleSearch(target.value)}
            placeholder="Search"
            inputProps={{
              autoComplete: 'off',
              maxLength: SEARCH_TEXT_MAX_LENGTH,
            }}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={() => null}>
                    <SearchRounded />
                  </IconButton>
                </InputAdornment>
              ),
            }}
            size="small"
          />
        </Stack>
        <Grid container className={styles.List}>
          <Grid container className={styles.ListRow}>
            <Grid item container className={styles.ListCategory}>
              <Typography variant="body2" color="text.primary" fontWeight={500}>
                Start a new form
              </Typography>
            </Grid>
            <Grid item container alignItems="center" className={styles.ListItems}>
              <TemplateItem name="Blank" onOpen={() => router.push('/forms/new')} />
              {lastUsedTemplates.map((template) => (
                <TemplateItem
                  key={template.id}
                  thumb={template.logo[2]}
                  name={template.name}
                  onOpen={() => {
                    setTemplateId(template.id);
                    router.push(`/forms/new?templateId=${template.id}`);
                  }}
                />
              ))}
            </Grid>
          </Grid>

          {templates.map((group) => (
            <Grid container key={group.formTemplateCategoryId} className={styles.ListRow}>
              <Grid item container className={styles.ListCategory}>
                <Typography variant="body2" color="text.primary" fontWeight={500}>
                  {group.formTemplateCategoryName}
                </Typography>
              </Grid>
              <Grid item container alignItems="center" className={styles.ListItems}>
                {group.records.map((template) => (
                  <TemplateItem
                    key={template.id}
                    thumb={template.logo[2]}
                    name={template.name}
                    onOpen={() => {
                      setTemplateId(template.id);
                      router.push(`/forms/new?templateId=${template.id}`);
                    }}
                  />
                ))}
              </Grid>
            </Grid>
          ))}
        </Grid>
      </DialogContent>

      <DialogActions>
        <Button size="small" variant="contained" onClick={handleClose}>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}

TemplateGallery.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
};

export default TemplateGallery;
