import React, { useEffect } from 'react';
import { CheckCircle } from '@mui/icons-material';

import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import {
  OAUTH_RESPONSE_WITH_CODE,
  OAUTH_RESPONSE_WITH_ERROR,
} from '@/modules/feeds/Editor/components/FormElements/Authorization/constants';

import { OAuthFeedType } from '@/modules/feeds/Editor/components/FormElements/Authorization/types';

import { isConnectedSelector, oAuthClientIdSelector, typeSelector } from '@/modules/feeds/Editor/redux/selectors';
import { getOAuthClientIdAction, getOAuthTokenAction } from '@/modules/feeds/Editor/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import { useAppDispatch, useAppSelector } from '@/modules/@common/store/hooks';
import { Button, LinearProgress, Stack, Typography } from '@/mui/components';

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

const handleOpenAuthPopup = (type: OAuthFeedType, clientId: string) => {
  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/${type.toLowerCase()}?clientId=${clientId}`,
    'Anyclip Authentication',
    `scrollbars=no, resizable=no, copyhistory=no, popup, width=${WIDTH}, height=${HEIGHT}, top=${y}, left=${x}`,
  );
};

function Authorization() {
  const dispatch = useAppDispatch();

  const isConnected = useAppSelector(isConnectedSelector);
  const type = useAppSelector(typeSelector) as OAuthFeedType;
  const oAuthClientId = useAppSelector(oAuthClientIdSelector);

  const handleAuthResponse = (responseEvent: { data: { type: string; payload: string } }) => {
    if (responseEvent?.data?.type === OAUTH_RESPONSE_WITH_CODE) {
      dispatch(getOAuthTokenAction({ code: responseEvent?.data.payload }));
    }

    if (responseEvent?.data?.type === OAUTH_RESPONSE_WITH_ERROR) {
      dispatch(
        showNotificationAction({
          type: TYPE_ERROR,
          message: `Can't authorize. Please try again later. If the problem persists, please contact support. Error: ${
            responseEvent?.data.payload
          }`,
        }),
      );
    }
  };

  useEffect(() => {
    if (type) {
      dispatch(getOAuthClientIdAction());
    }

    window.addEventListener('message', handleAuthResponse);
    return () => window.removeEventListener('message', handleAuthResponse);
  }, [type]);

  return (
    <Stack fullWidth direction="row" alignItems="center" spacing={2}>
      {!isConnected && !oAuthClientId && (
        <Stack fullWidth justifyContent="center" className={styles.Wrapper}>
          <LinearProgress color="primary" />
        </Stack>
      )}

      {isConnected && (
        <Stack direction="row" fullWidth alignItems="center" spacing={2} className={styles.Wrapper}>
          <CheckCircle fontSize="medium" htmlColor="success.dark" />
          <Typography variant="body2" color="success.dark" fontWeight={600}>
            Connected
          </Typography>
        </Stack>
      )}

      {!isConnected && oAuthClientId && (
        <Button fullWidth size="small" onClick={() => handleOpenAuthPopup(type, oAuthClientId)}>
          Connect to TikTok
        </Button>
      )}
    </Stack>
  );
}

export default Authorization;
