/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import FilledInput from '@mui/material/FilledInput';
import { styled } from '@mui/material/styles';
import { SecurityLabelKind } from '@sophie/shared';
import { autorun } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useCallback, useEffect, useState } from 'react';

import Service from '../../stores/Service';

import GoButton from './GoButton';
import LocationOverlayInput from './LocationOverlayInput';
import SecurityLabel from './SecurityLabel';
import UrlOverlay from './UrlOverlay';

const LocationTextFieldRoot = styled(FilledInput, {
  name: 'LocationTextField',
  slot: 'Root',
})(({ theme }) => ({
  padding: '0 12px',
  flex: '1 0 200px',
  borderRadius: 18,
  '&.Mui-focused': {
    outline: `2px solid ${theme.palette.primary.main}`,
  },
}));

function LocationTextField({
  service,
}: {
  service: Service | undefined;
}): JSX.Element {
  const [inputFocused, setInputFocused] = useState(false);
  const [changed, setChanged] = useState(false);
  const [value, setValue] = useState('');

  const resetValue = useCallback(() => {
    setValue(service?.currentUrl ?? '');
    setChanged(false);
  }, [service, setChanged, setValue]);

  useEffect(
    () =>
      autorun(() => {
        resetValue();
      }),
    [resetValue],
  );

  const inputRefCallback = useCallback(
    (input: HTMLInputElement) => {
      setInputFocused(
        document.activeElement !== null && document.activeElement === input,
      );
    },
    [setInputFocused],
  );

  return (
    <LocationTextFieldRoot
      inputComponent={LocationOverlayInput}
      inputProps={{
        'aria-label': 'Location',
        spellCheck: false,
        overlayVisible: !inputFocused && !changed,
        overlay: (
          <UrlOverlay
            url={service?.currentUrl ?? ''}
            alert={service?.hasSecurityLabelWarning ?? false}
          />
        ),
      }}
      inputRef={inputRefCallback}
      onFocus={() => setInputFocused(true)}
      onBlur={() => setInputFocused(false)}
      onChange={({ target: { value: newValue } }) => {
        setValue(newValue);
        setChanged(true);
      }}
      onKeyDown={(event) => {
        switch (event.key) {
          case 'Escape':
            resetValue();
            break;
          case 'Enter':
            service?.go(value);
            break;
          default:
            // Nothing to do, let the key event through.
            return;
        }
        event.preventDefault();
        event.stopPropagation();
      }}
      size="small"
      fullWidth
      hiddenLabel
      disableUnderline
      startAdornment={
        <SecurityLabel
          kind={service?.securityLabel ?? SecurityLabelKind.Empty}
          changed={changed}
          position="start"
        />
      }
      endAdornment={
        changed ? (
          <GoButton onClick={() => service?.go(value)} position="end" />
        ) : undefined
      }
      value={value}
    />
  );
}

export default observer(LocationTextField);
