'use client';

import React, { useState } from 'react';
import { Button } from 'antd';
import { useSelectedLayoutSegment, usePathname } from 'next/navigation';
import { Link } from '../../navigation';
import { AUTH_TOKEN_KEY, AUTH_USER } from '../../constants/common';
import { deleteStorageKey } from '../../hooks/useLocalStorage';
import { i18nText } from '../../i18nKeys';
import { DeleteAccountModal } from '../Modals/DeleteAccountModal';
import { getMenuConfig } from '../../utils/account';

export const AccountMenu = ({ locale }: { locale: string }) => {
    const selectedLayoutSegment = useSelectedLayoutSegment();
    const pathname = selectedLayoutSegment || '';
    const paths = usePathname();
    const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false);
    const menu: { path: string, title: string, count?: number }[] = getMenuConfig(locale);

    const onLogout = () => {
        deleteStorageKey(AUTH_TOKEN_KEY);
        deleteStorageKey(AUTH_USER);
        window?.location?.replace(`/${paths.split('/')[1]}/`);
    };

    const onDeleteAccount = () => setShowDeleteModal(true);

    return (
        <ul className="list-sidebar">
            {menu.map(({ path, title, count }) => (
                <li key={path} className="list-sidebar__item">
                    <Link href={`/account/${path}` as any} className={path === pathname ? 'active' : ''}>
                        {title}
                        {count ? (
                            <span className="count">{count}</span>
                        ) : null}
                    </Link>
                </li>
            ))}
            <li className="list-sidebar__item">
                <Button
                    type="link"
                    onClick={onLogout}
                    className="b-button__logout"
                >
                    {i18nText('logout', locale)}
                </Button>
            </li>
            <li className="list-sidebar__item">
                <Button
                    type="link"
                    onClick={onDeleteAccount}
                    className="b-button__logout"
                >
                    {i18nText('deleteAcc', locale)}
                </Button>
                <DeleteAccountModal
                    open={showDeleteModal}
                    handleCancel={() => setShowDeleteModal(false)}
                />
            </li>
        </ul>
    );
};
