import { useEffect } from 'react';

import { Center, Heading, Image, Text } from '@chakra-ui/react';
import { useNavigate, useParams } from 'react-router-dom';

import avatar_generic from '@/assets/images/avatar_generic.svg';
import { PageLayoutInfoCenter } from '@/components/Layout/PageLayoutInfoCenter';
import { TopBar } from '@/components/TopBar/TopBar';
import { isDevelopmentEnvironment } from '@/environment';
import { useSessionService } from '@/service/session';
import { b64_to_utf8 } from '@/utils/sso';

export const SSOPage = () => {
  const { data, keepConnected, token } = useParams();
  console.log(`- data: ${data}`);
  console.log(`- keepConnected: ${keepConnected}`);
  console.log(`- token: ${token}`);
  const navigate = useNavigate();
  const { isConnected, setToken, login, clearToken } = useSessionService();
  useEffect(() => {
    if (token) {
      setToken(token);
    } else {
      clearToken();
    }
  }, [token, setToken, clearToken]);
  const delay = isDevelopmentEnvironment() ? 2000 : 2000;
  useEffect(() => {
    if (isConnected) {
      const destination = data ? b64_to_utf8(data) : '/';
      console.log(`program redirect to: ${destination} (${delay}ms)`);
      setTimeout(() => {
        navigate(`/${destination}`);
      }, delay);
    }
  }, [isConnected]);
  /*
  const [searchParams] = useSearchParams();
  console.log(`data: ${searchParams.get('data')}`);
  console.log(`keepConnected: ${searchParams.get('keepConnected')}`);
  console.log(`token: ${searchParams.get('token')}`);
  const dataFromParam = useGetCreateActionParams();
  console.log(`data group: ${JSON.stringify(dataFromParam, null, 2)}`);
  */
  return (
    <>
      <TopBar />
      <PageLayoutInfoCenter width="35%" gap="15px">
        <Center w="full">
          <Heading size="xl">LOGIN (after SSO) </Heading>
        </Center>

        <Center w="full">
          <Image src={avatar_generic} boxSize="150px" borderRadius="full" />
        </Center>
        {!isConnected  && (
          <Text>
            <b>ERROR: </b> connection fail !
          </Text>
        )}
        {isConnected && (
          <>
            <Text>
              <b>Connected: </b> Redirect soon!
            </Text>
            <Text>
              <b>Welcome back: </b> {login}
            </Text>
          </>
        )}
      </PageLayoutInfoCenter>
    </>
  );
};
