import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import dynamic from 'next/dynamic';
import { CloseRounded, FileUploadRounded, SearchRounded } from '@mui/icons-material';

import { PCN_POST_VIDEO, VIDEO_SCREEN_RECORDING_TMP } from '@/modules/@common/acl/constants';

import { getIsWordpressMode, getIsWPVideoMode } from '@/modules/@common/app/helpers';
import { addQueriesAction } from '@/modules/@common/location/redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserContentOwnersSelector, getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import {
  playlistTypeSelector,
  querySelector,
  suggesterOptionsSelector,
} from '@/modules/editorial/editorialSearch/reduxSearch/selectors';
import {
  queryAction,
  searchEventAction,
  searchFromSuggesterAction,
  searchSuggesterAction,
  showUploaderAction,
  suggesterOptionsAction,
} from '@/modules/editorial/editorialSearch/reduxSearch/slices';
import {
  configSelector,
  defaultEmptyFilterOrderSelector,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/selectors';
import {
  configAction,
  isFilterDirtyAction,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';
import { aiPlaylistIdAction, showDividerAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { getDefaultTabAfterSearchOrFilter } from '@/modules/editorial/helpers/videoTab';
import { aiPlaylistModeSelector } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/selectors';
import { setAiPlaylistModeAction } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/slices';
import { isMobileApp } from '@/modules/layout/helpers';

import {
  DEFAULT_FILTER_NAMES,
  getDefaultRelevanceOrderConfig,
  getEmptySearchOrderConfig,
} from '@/modules/editorial/editorialSearchFilter/filterConfig';
import {
  Autocomplete,
  Button,
  IconButton,
  InputAdornment,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from '@/mui/components';

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

const Recorder = dynamic(() => import('@/modules/editorial/Recorder'), {
  ssr: false,
});
const VideoUploader = dynamic(() => import('@/modules/uploaderNew'), {
  ssr: false,
});

const INPUT_TEXT_MAX_LENGTH = 1024;

function SearchComponent() {
  const dispatch = useDispatch();
  const aiPlaylistMode = useSelector(aiPlaylistModeSelector);
  const config = useSelector(configSelector);
  const defaultEmptyFilterOrder = useSelector(defaultEmptyFilterOrderSelector);
  const ownerIds = useSelector(getUserContentOwnersSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);

  const query = useSelector(querySelector);
  const playlistType = useSelector(playlistTypeSelector);
  const suggesterOptions = useSelector(suggesterOptionsSelector);

  const [value, setValue] = useState(query ?? '');

  const isWpMode = getIsWordpressMode() || getIsWPVideoMode();

  const handleSubmit = (event, newValue) => {
    event.preventDefault();
    setValue(newValue);

    dispatch(queryAction(newValue));

    dispatch(searchEventAction());
    dispatch(
      addQueriesAction({
        videoTabs: getDefaultTabAfterSearchOrFilter(userPermissions)?.value,
      }),
    );
    dispatch(suggesterOptionsAction([]));
    dispatch(
      searchSuggesterAction({
        clearSuggestions: true,
      }),
    );
    dispatch(searchFromSuggesterAction(false));
  };

  const onInputChange = (event, queryText) => {
    dispatch(suggesterOptionsAction([]));
    setValue(queryText);
    dispatch(isFilterDirtyAction(true));
    if (queryText.length >= 3) {
      dispatch(
        searchSuggesterAction({
          prefix: queryText,
        }),
      );
    }

    const updatedConfig = Object.keys(config).reduce((acc, key) => {
      const defaultOrderConfig = defaultEmptyFilterOrder
        ? getEmptySearchOrderConfig()
        : getDefaultRelevanceOrderConfig();

      const oneItemConfig =
        key === DEFAULT_FILTER_NAMES.order
          ? defaultOrderConfig
          : {
              [key]: {
                ...config[key],
                filters: [config[key].filters[0]],
              },
            };

      return {
        ...acc,
        ...oneItemConfig,
      };
    }, {});

    dispatch(configAction(updatedConfig));
  };

  const handleClose = () => {
    dispatch(setAiPlaylistModeAction(false));
    dispatch(aiPlaylistIdAction(0));
    dispatch(showDividerAction(false));
  };

  useEffect(() => () => dispatch(queryAction('')), []);

  useEffect(() => setValue(query ?? ''), [query]);

  return (
    <>
      <Stack
        spacing={2}
        direction="row"
        fullWidth
        alignItems="center"
        data-id="searchComponent"
        className={styles.Container}
      >
        {aiPlaylistMode && (
          <>
            <IconButton color="neutral" onClick={handleClose}>
              <CloseRounded />
            </IconButton>

            <Typography variant="h6" fontWeight={400}>
              {playlistType === 'RECENT' ? 'Recent Block Filter' : 'Trending Block Filter'}
            </Typography>
          </>
        )}
        {!aiPlaylistMode && (
          <>
            <form className={styles.Form} onSubmit={(event) => handleSubmit(event, value)}>
              <Autocomplete
                freeSolo
                data-id="input"
                options={suggesterOptions.map((option) => ({
                  label: option,
                  value: `-${option}-`,
                }))}
                disableClearable
                isOptionEqualToValue={() => false}
                filterOptions={(x) => x}
                onInputChange={onInputChange}
                onChange={(e, value$, reason) => {
                  dispatch(searchFromSuggesterAction(reason === 'selectOption'));
                  const valueRes = value$?.label ?? value;

                  if (reason === 'selectOption') {
                    handleSubmit(e, valueRes);
                  }
                }}
                value={value}
                renderInput={(params) => {
                  const InputProps = {
                    ...params.InputProps,
                    classes: {
                      notchedOutline: styles.NotchedOutline,
                    },
                    startAdornment: (
                      <Tooltip title="Search videos">
                        <InputAdornment position="start">
                          <IconButton size="large" onClick={(event) => handleSubmit(event, value)}>
                            <SearchRounded />
                          </IconButton>
                        </InputAdornment>
                      </Tooltip>
                    ),
                  };

                  InputProps.endAdornment = value ? (
                    <InputAdornment position="end">
                      <IconButton
                        onClick={() => {
                          dispatch(searchFromSuggesterAction(false));
                          dispatch(suggesterOptionsAction([]));

                          setValue('');

                          dispatch(queryAction(''));
                        }}
                      >
                        <CloseRounded />
                      </IconButton>
                    </InputAdornment>
                  ) : null;

                  return (
                    <TextField
                      {...params}
                      placeholder="Search Videos"
                      inputProps={{
                        ...params.inputProps,
                        maxLength: INPUT_TEXT_MAX_LENGTH,
                      }}
                      InputProps={InputProps}
                    />
                  );
                }}
              />
            </form>
            {hasPermission(PCN_POST_VIDEO, userPermissions) && ownerIds.some((i) => i.publisherOwnsContent) && (
              <Stack spacing={2} direction="row" alignItems="center">
                {hasPermission(VIDEO_SCREEN_RECORDING_TMP, userPermissions) && !isWpMode && <Recorder />}

                {!isMobileApp && (
                  <Tooltip title="Upload Video">
                    <Button
                      size="small"
                      color="neutral"
                      variant="outlined"
                      startIcon={<FileUploadRounded />}
                      square
                      onClick={(v) => dispatch(showUploaderAction(v))}
                    />
                  </Tooltip>
                )}
              </Stack>
            )}
          </>
        )}
      </Stack>
      <VideoUploader />
    </>
  );
}

export default SearchComponent;
