'use client'

import React, { FC, useState, useEffect } from 'react';
import { Button } from 'antd';
import { useSelectedLayoutSegment } from 'next/navigation';
import { Link } from '../../../navigation';
import { AUTH_TOKEN_KEY } from '../../../constants/common';
import { useLocalStorage } from '../../../hooks/useLocalStorage';
import { AuthModal } from '../../Modals/AuthModal';
import { i18nText } from '../../../i18nKeys';

type HeaderAuthLinksProps = {
    locale: string;
    separatorClass?: string;
};

function HeaderAuthLinks ({
    locale,
    separatorClass = 'b-header__nav__list__line'
}: HeaderAuthLinksProps) {
    const [isOpenModal, setIsOpenModal] = useState<boolean>(false);
    const [mode, setMode] = useState<'enter' | 'register' | 'reset' | 'finish'>('enter');
    const selectedLayoutSegment = useSelectedLayoutSegment();
    const pathname = selectedLayoutSegment || '';
    const [token, setToken] = useLocalStorage(AUTH_TOKEN_KEY, '');

    useEffect(() => {
        if (!isOpenModal) {
            setMode('enter');
        }
    }, [isOpenModal]);

    const onOpen = (mode: 'enter' | 'register' | 'reset' | 'finish') => {
        setMode(mode);
        setIsOpenModal(true);
    };

    return token
        ? (
            <li>
                <Link href={'/account/sessions/upcoming' as any} className={pathname === 'account' ? 'active' : ''}>
                    {i18nText('account', locale)}
                </Link>
            </li>
        )
        : (
            <>
                <li>
                    <Button
                        className="b-header__auth"
                        type="link"
                        onClick={() => onOpen('register')}
                    >
                        {i18nText('registration', locale)}
                    </Button>
                </li>
                <li>
                    <span className={separatorClass}>|</span>
                </li>
                <li>
                    <Button
                        className="b-header__auth"
                        type="link"
                        onClick={() => onOpen('enter')}
                    >
                        {i18nText('enter', locale)}
                    </Button>
                </li>
                <AuthModal
                    open={isOpenModal}
                    handleCancel={() => setIsOpenModal(false)}
                    mode={mode}
                    updateMode={setMode}
                    updateToken={setToken}
                />
            </>
    );
}

export default HeaderAuthLinks;
