import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';

import { AUTH_TYPES } from '../constants';
import { emailRegExp } from '@/modules/@common/constants/validation';

import { isFormLoadingSelector } from '@/modules/auth/common/redux/selectors';
import { emailSelector } from '@/modules/auth/Login/redux/selectors';
import { getSsoLinkAction, setEmailAction } from '@/modules/auth/Login/redux/slices';

import Layout from '@/modules/auth/common/components/Layout/Layout';
import useSsoBackgroundLogin from '@/modules/auth/common/useSsoBackgroundLogin';
import useSsoLocalStorageEmails from '@/modules/auth/SsoLogin/components/useSsoLocalStorageEmails';
import GoogleIconColored from '@/mui/customIcons/UnstyledIcons/GoogleIconColored';
import { Autocomplete, Button, InputAdornment, Stack, TextField } from '@/mui/components';
import { CustomPeople } from '@/mui/components/CustomIcon';

function Sso() {
  const router = useRouter();
  const dispatch = useDispatch();
  const isFormLoading = useSelector(isFormLoadingSelector);
  const email = useSelector(emailSelector);
  const [emailError, setEmailError] = useState('');
  const { emails, saveEmailToLocalStorage } = useSsoLocalStorageEmails();
  const { ssoLoginByUParam } = useSsoBackgroundLogin();
  const { u } = router.query;

  const handleEmailChange = (value) => dispatch(setEmailAction(value));
  const handleEmailLogin = (event) => {
    event.preventDefault();

    if (emailRegExp.test(email?.trim() ?? '')) {
      setEmailError('');
      saveEmailToLocalStorage(email);
      dispatch(
        getSsoLinkAction({
          type: AUTH_TYPES.byEmail,
          email,
        }),
      );
    } else {
      setEmailError('The email you entered is incorrect');
    }
  };
  const handleGoogleLogin = () => {
    dispatch(
      getSsoLinkAction({
        type: AUTH_TYPES.byGoogle,
      }),
    );
  };

  useEffect(() => ssoLoginByUParam(), []);

  return (
    <Layout
      shouldHideContent={!!u}
      title="Sign in with SSO"
      firstSection={
        <Stack component="form" disabled={isFormLoading} onSubmit={handleEmailLogin} spacing={3} fullWidth>
          <Autocomplete
            data-id="autocomplete-email"
            freeSolo
            disableClearable
            value={email}
            optionValueKey="label"
            options={emails || []}
            onChange={(e, email$) => handleEmailChange(email$?.label ?? email$ ?? '')}
            onOpen={() => setEmailError('')}
            renderInput={(params) => (
              <TextField
                {...params}
                data-id="autocomplete-email-input"
                value=""
                variant="outlined"
                placeholder="Email"
                helperText={emailError}
                onChange={({ target }) => handleEmailChange(target.value)}
                error={!!emailError}
                InputProps={{
                  ...params.InputProps,
                  startAdornment: (
                    <InputAdornment position="start">
                      <CustomPeople />
                    </InputAdornment>
                  ),
                }}
              />
            )}
          />
          <div>
            <Button
              type="submit"
              data-id="sso-submit"
              variant="contained"
              color="primary"
              disabled={isFormLoading}
              size="large"
              shape="circular"
            >
              Sign in
            </Button>
          </div>
        </Stack>
      }
      secondSection={
        <Button
          data-id="signin-sso"
          variant="outlined"
          shape="circular"
          color="info"
          disabled={isFormLoading}
          onClick={handleGoogleLogin}
          startIcon={<GoogleIconColored />}
        >
          Sign in with Google
        </Button>
      }
    />
  );
}

export default Sso;
