import * as React from 'react';
import { useTranslation } from 'next-i18next';
import { useRouter } from 'next/router';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import SearchRoundedIcon from '@mui/icons-material/SearchRounded';
import InputAdornment from '@mui/material/InputAdornment';
import IconButton from '@mui/material/IconButton';

import { Pages } from 'src/constants';

export default function SearchInput() {
  const [inputValue, setInputValue] = React.useState('');

  const { t } = useTranslation();
  const router = useRouter();

  const handleSearch = (type: 'input' | 'icon') => () => {
    // console.log(encodeURIComponent(inputValue));
    switch (type) {
      case 'input':
        inputValue &&
          router.push(
            `${Pages.Search}?query=${encodeURIComponent(inputValue)}`
          );
        break;
      case 'icon':
        router.push(Pages.Search);
        break;
      default:
        break;
    }
  };

  return (
    <>
      <Box
        sx={{
          display: {
            xs: 'none',
            md: 'block',
          },
        }}
      >
        <TextField
          id="outlined-search"
          placeholder={t('search.input_placeholder')}
          type="search"
          size="small"
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchRoundedIcon color="inherit" />
              </InputAdornment>
            ),
          }}
          value={inputValue}
          onChange={(event) => setInputValue(event.target.value)}
          onSubmit={handleSearch('input')}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              handleSearch('input')();
            }
          }}
        />
      </Box>
      <Box
        sx={{
          display: {
            xs: 'block',
            md: 'none',
          },
        }}
      >
        <SearchInputMobile onClick={handleSearch('icon')} />
      </Box>
    </>
  );
}

export function SearchInputMobile(props: { onClick?: () => void }) {
  const { onClick } = props;

  return (
    <IconButton aria-label="search button" size="small" onClick={onClick}>
      <SearchRoundedIcon fontSize="inherit" />
    </IconButton>
  );
}
