import React from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';

import { TYPE_FACEBOOK, TYPE_YOUTUBE } from '../../constants';

import * as selectors from '../../redux/selectors';
import { removeErrorByPropAction } from '../../redux/slices';
import { getInputPropsByName } from '@/modules/@common/Form/helpers';

import { Button, FormHelperText, Stack } from '@/mui/components';

const openAuthPopup = (authProvider, clientId) => {
  const AUTH_BASE_URL = process.env.APP_ENV_BASE_URL;

  const WIDTH = 562;
  const HEIGHT = 670;

  const y = window.top.outerHeight / 2 + window.top.screenY - HEIGHT / 2;
  const x = window.top.outerWidth / 2 + window.top.screenX - WIDTH / 2;
  window.open(
    `${AUTH_BASE_URL}/auth/${authProvider}?cid=${clientId}`,
    'Anyclip Authentication',
    `scrollbars=no, resizable=no, copyhistory=no, popup, width=${WIDTH}, height=${HEIGHT}, top=${y}, left=${x}`,
  );
};

export function SignButton(props) {
  const dispatch = useDispatch();
  const type = useSelector(selectors.typeSelector);
  const accessToken = useSelector(selectors.accessTokenSelector);
  const userName = useSelector(selectors.userNameSelector);
  const scheme = useSelector(selectors.schemeSelector);

  let title = '';
  let signOnClick = () => null;

  if (type === TYPE_YOUTUBE) {
    title = 'Youtube';
    signOnClick = () => {
      openAuthPopup('google', process.env.APP_G_CLIENT_ID);
    };
  } else if (type === TYPE_FACEBOOK) {
    title = 'Facebook';
    signOnClick = () => {
      openAuthPopup('facebook', process.env.APP_FB_CLIENT_ID);
    };
  }

  const inputSchemeData = getInputPropsByName(scheme, ['platform']);

  return (
    <Stack fullWidth>
      <Button
        size={props.size}
        fullWidth
        color={accessToken ? 'success' : 'primary'}
        disabled={props.disabled || !title}
        name={inputSchemeData.name}
        onClick={() => {
          dispatch(removeErrorByPropAction(['platform']));

          if (!accessToken) {
            signOnClick();
          }
        }}
      >
        {accessToken ? `${userName ?? ''} signed in with ` : 'Sign in with '}
        {title}
      </Button>
      {inputSchemeData.error && <FormHelperText error>{inputSchemeData.helperText}</FormHelperText>}
    </Stack>
  );
}

SignButton.propTypes = {
  size: PropTypes.oneOf(['xSmall', 'small', 'medium', 'large']),
  disabled: PropTypes.bool,
};
