// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License for license information.

import {useDispatch, useSelector} from 'react-redux';

import {getCurrentUser} from 'mattermost-redux/selectors/entities/common';

import React, {useCallback, useEffect, useState} from 'react';

import {getUser} from 'mattermost-redux/selectors/entities/users';

import {GlobalState} from 'mattermost-redux/types/store';

import {getCustomEmojiByName, getCustomEmojisByName} from 'mattermost-redux/actions/emojis';

import {FormattedMessage} from 'react-intl';

import {getRHSBadge, getRHSUser, getRHSView, getPrevRHSView, getRHSTypeId, getRHSTypeName} from 'selectors';
import {RHS_STATE_ALL, RHS_STATE_DETAIL, RHS_STATE_OTHER, RHS_STATE_MY, RHS_STATE_TYPES, RHS_STATE_TYPE_BADGES} from '../../constants';
import {RHSState} from 'types/general';
import {openCreateBadgeModal, openCreateTypeModal, openEditBadgeModal, setRHSBadge, setRHSUser, setRHSView} from 'actions/actions';
import {BadgeDetails, BadgeID} from 'types/badges';
import Client from '../../client/api';

import TooltipWrapper from '../user_popover/tooltip_wrapper';

import UserBadges from './user_badges';
import BadgeDetailsComponent from './badge_details';
import AllBadges from './all_badges';
import AllTypes from './all_types';

import './all_badges.scss';

const RHS: React.FC = () => {
    const dispatch = useDispatch();
    const currentView = useSelector(getRHSView);
    const prevView = useSelector(getPrevRHSView);
    const currentBadge = useSelector(getRHSBadge);
    const currentUserID = useSelector(getRHSUser);
    const filterTypeId = useSelector(getRHSTypeId);
    const filterTypeName = useSelector(getRHSTypeName);
    const currentUser = useSelector((state: GlobalState) => getUser(state, (currentUserID as string)));
    const myUser = useSelector(getCurrentUser);

    const [canEditType, setCanEditType] = useState(false);
    const [canCreateType, setCanCreateType] = useState(false);
    const [canCreateBadge, setCanCreateBadge] = useState(false);

    useEffect(() => {
        const client = new Client();
        client.getTypes().then((resp) => {
            setCanEditType(resp.can_edit_type);
            setCanCreateType(resp.can_create_type);
            setCanCreateBadge(resp.types.length > 0 || resp.can_create_type);
        });
    }, []);

    const showTabs = currentView === RHS_STATE_MY || currentView === RHS_STATE_ALL || currentView === RHS_STATE_TYPES;

    const handleCreateBadge = useCallback(() => {
        dispatch(openCreateBadgeModal());
    }, [dispatch]);

    const handleCreateType = useCallback(() => {
        dispatch(openCreateTypeModal());
    }, [dispatch]);

    const renderTabs = () => {
        if (!showTabs) {
            return null;
        }

        return (
            <div className='AllBadges__header'>
                <div className='AllBadges__tabs'>
                    <button
                        className={'AllBadges__tab' + (currentView === RHS_STATE_MY ? ' AllBadges__tab--active' : '')}
                        onClick={() => dispatch(setRHSView(RHS_STATE_MY))}
                    >
                        <FormattedMessage
                            id='badges.rhs.my_badges'
                            defaultMessage='Мои'
                        />
                    </button>
                    <button
                        className={'AllBadges__tab' + (currentView === RHS_STATE_ALL ? ' AllBadges__tab--active' : '')}
                        onClick={() => dispatch(setRHSView(RHS_STATE_ALL))}
                    >
                        <FormattedMessage
                            id='badges.rhs.all_badges'
                            defaultMessage='Все достижения'
                        />
                    </button>
                    {canEditType && (
                        <button
                            className={'AllBadges__tab' + (currentView === RHS_STATE_TYPES ? ' AllBadges__tab--active' : '')}
                            onClick={() => dispatch(setRHSView(RHS_STATE_TYPES))}
                        >
                            <FormattedMessage
                                id='badges.rhs.types'
                                defaultMessage='Типы'
                            />
                        </button>
                    )}
                </div>
            </div>
        );
    };

    const renderFab = () => {
        if (currentView === RHS_STATE_ALL && canCreateBadge) {
            return (
                <TooltipWrapper
                    tooltipContent={
                        <FormattedMessage
                            id='badges.rhs.create_badge'
                            defaultMessage='Создать достижение'
                        />
                    }
                >
                    <button
                        className='AllBadges__fab'
                        onClick={handleCreateBadge}
                    >
                        {'+'}
                    </button>
                </TooltipWrapper>
            );
        }
        if (currentView === RHS_STATE_TYPES && canCreateType) {
            return (
                <TooltipWrapper
                    tooltipContent={
                        <FormattedMessage
                            id='badges.rhs.create_type'
                            defaultMessage='Создать тип'
                        />
                    }
                >
                    <button
                        className='AllBadges__fab'
                        onClick={handleCreateType}
                    >
                        {'+'}
                    </button>
                </TooltipWrapper>
            );
        }
        return null;
    };

    const renderContent = () => {
        switch (currentView) {
        case RHS_STATE_TYPES:
            return <AllTypes/>;
        case RHS_STATE_TYPE_BADGES:
            return (
                <AllBadges
                    filterTypeId={filterTypeId}
                    filterTypeName={filterTypeName}
                    actions={{
                        setRHSView: (view: RHSState) => dispatch(setRHSView(view)),
                        setRHSBadge: (badge: BadgeID | null) => dispatch(setRHSBadge(badge)),
                        getCustomEmojisByName: (names: string[]) => dispatch(getCustomEmojisByName(names)),
                        openCreateBadgeModal: () => dispatch(openCreateBadgeModal()),
                    }}
                />
            );
        case RHS_STATE_ALL:
            return (
                <AllBadges
                    actions={{
                        setRHSView: (view: RHSState) => dispatch(setRHSView(view)),
                        setRHSBadge: (badge: BadgeID | null) => dispatch(setRHSBadge(badge)),
                        getCustomEmojisByName: (names: string[]) => dispatch(getCustomEmojisByName(names)),
                        openCreateBadgeModal: () => dispatch(openCreateBadgeModal()),
                    }}
                />
            );
        case RHS_STATE_DETAIL:
            return (
                <BadgeDetailsComponent
                    badgeID={currentBadge}
                    currentUserID={myUser.id}
                    prevView={prevView}
                    actions={{
                        setRHSView: (view: RHSState) => dispatch(setRHSView(view)),
                        setRHSUser: (user: string | null) => dispatch(setRHSUser(user)),
                        getCustomEmojiByName: (names: string) => dispatch(getCustomEmojiByName(names)),
                        openEditBadgeModal: (badge: BadgeDetails) => dispatch(openEditBadgeModal(badge)),
                    }}
                />
            );
        case RHS_STATE_OTHER:
            return (
                <UserBadges
                    user={currentUser}
                    isCurrentUser={false}
                    currentUserID={myUser.id}
                    actions={{
                        setRHSView: (view: RHSState) => dispatch(setRHSView(view)),
                        setRHSBadge: (badge: BadgeID | null) => dispatch(setRHSBadge(badge)),
                        getCustomEmojisByName: (names: string[]) => dispatch(getCustomEmojisByName(names)),
                    }}
                />
            );
        case RHS_STATE_MY:
        default:
            return (
                <UserBadges
                    user={myUser}
                    isCurrentUser={true}
                    currentUserID={myUser.id}
                    actions={{
                        setRHSView: (view: RHSState) => dispatch(setRHSView(view)),
                        setRHSBadge: (badge: BadgeID | null) => dispatch(setRHSBadge(badge)),
                        getCustomEmojisByName: (names: string[]) => dispatch(getCustomEmojisByName(names)),
                    }}
                />
            );
        }
    };

    const needsWrapper = showTabs || currentView === RHS_STATE_TYPE_BADGES;

    if (needsWrapper) {
        return (
            <div className='AllBadges'>
                {renderTabs()}
                <div className='AllBadges__content'>
                    {renderContent()}
                    {renderFab()}
                </div>
            </div>
        );
    }

    return renderContent();
};

export default RHS;
