import * as React from 'react';
import { useEffect, useState, useImperativeHandle } from 'react';
import { Dropdown, List, Menu, Popover } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { ReactComponent as ServerIcon } from '../images/server.svg';
import { ReactComponent as SettingsIcon } from '../images/settings.svg';
import { ReactComponent as TickIcon } from '../images/tick.svg';
import { DeployInfo, HelpDocumentLink, PageStep, Platfrom, regionOptions } from '../common';
import { FormattedMessage } from 'react-intl';

interface ActionProps {
    cRef: any;
    rpc: any;
    language: string;
    languageMap: { [key: string]: string };
    platform: string;
    initStage: string;
    initRegion: string;
	tencentOnly: boolean;
    deployInfo?: DeployInfo;
    setStep: (value: PageStep) => void;
    reload: (data: { region?: string; stage?: string }) => void;
    logout: () => void;
}

const stageOptions = [
    { text: 'Test', value: 'test' },
    { text: 'Pre-Production', value: 'pre' },
    { text: 'Production', value: 'prod' },
];

export const InfoStepActions = (props: ActionProps) => {
    const { cRef, rpc, language, languageMap, platform, initStage, initRegion, tencentOnly, deployInfo, setStep, reload, logout } =
        props;
    const [stage, setStage] = useState<string>(initStage);
    const [region, setRegion] = useState<string>(initRegion);
    const [regionName, setRegionName] = useState<string>();
    const [stageVisible, setStageVisible] = useState<boolean>(false);
    const [settingsVisible, setSettingsVisible] = useState<boolean>(false);

    const onSelectedRegion = async (item: { textId: string; value: string }) => {
        if (region !== item.value) {
            setRegion(item.value);
            setRegionName(languageMap[item.textId]);
            reload({ region: item.value });
        }
    };

    const onSelectedStage = async (value: string) => {
        setStageVisible(false);
        if (stage !== value) {
            setStage(value);
            reload({ stage: value });
        }
    };

    const openLink = (link: string) => {
        rpc.invoke('openWebLink', [link]);
    };

    const getScfLink = () => {
        // e.g: https://console.cloud.tencent.com/scf/list-detail?rid=1&ns=default&id=react-app-1_gnxtq
        if (deployInfo?.namespaceName) {
            const regionObj = regionOptions[platform].find((item: any) => item.value === deployInfo?.region);
            const regionId = regionObj?.regionId || 1;
            const namespace = deployInfo?.namespaceName || 'default';
            const link = `https://console.cloud.tencent.com/scf/list-detail?rid=${regionId}&ns=${namespace}&id=${deployInfo?.projectName}`;
            openLink(link);
        } else {
            const regionObj = regionOptions[platform].find((item: any) => item.value === region);
            const regionId = regionObj?.regionId || 1;
            openLink(`https://console.cloud.tencent.com/scf/list?rid=${regionId}&ns=default`);
        }
    };
    const getApiGwLink = () => {
        // e.g: https://console.cloud.tencent.com/apigateway/service-detail?rid=1&id=service-7gsdjc5c
        if (deployInfo?.serviceId) {
            const regionObj = regionOptions[platform].find((item: any) => item.value === deployInfo?.region);
            const regionId = regionObj?.regionId || 1;
            const link = `https://console.cloud.tencent.com/apigateway/service-detail?rid=${regionId}&id=${deployInfo?.serviceId}`;
            openLink(link);
        } else {
            const regionObj = regionOptions[platform].find((item: any) => item.value === region);
            const regionId = regionObj?.regionId || 1;
            openLink(`https://console.cloud.tencent.com/apigateway/service?rid=${regionId}`);
        }
    };
    const getFcLink = () => {
        // e.g: https://fcnext.console.aliyun.com/cn-hangzhou/services/react-app-1/function-detail/react-app-1_gnxtq/LATEST?tab=config
        if (deployInfo?.serviceName) {
            const link = `https://fcnext.console.aliyun.com/${deployInfo?.region}/services/${deployInfo?.serviceName}/function-detail/${deployInfo?.projectName}/LATEST?tab=config`;
            openLink(link);
        } else {
            openLink(`https://fcnext.console.aliyun.com/${region}/services`);
        }
    };

    const getPlatformMenu = () => {
        if (platform === Platfrom.TENCENT) {
            return (
                <>
                    <List.Item onClick={getScfLink}>
                        <FormattedMessage id='info.settings.tencent.scf' />
                    </List.Item>
                    <List.Item onClick={getApiGwLink}>
                        <FormattedMessage id='info.settings.tencent.apigw' />
                    </List.Item>
                </>
            );
        }
        if (platform === Platfrom.ALIBABA) {
            return (
                <List.Item onClick={getFcLink}>
                    <FormattedMessage id='info.settings.alibaba.fc' />
                </List.Item>
            );
        }
    };

    const regionMenu = (
        <Menu>
            {regionOptions[platform].map((item: any) => {
                return (
                    <Menu.Item>
                        <div className='selection-item' onClick={() => onSelectedRegion(item)}>
                            <span>{languageMap[item.textId]}</span>
                            {region === item.value ? <TickIcon className='vscode-icon small-icon' /> : ''}
                        </div>
                    </Menu.Item>
                );
            })}
        </Menu>
    );

    useImperativeHandle(cRef, () => ({
        getStage: () => stage,
    }));

    useEffect(() => {
        const regionObj = regionOptions[platform].find((item: any) => item.value === initRegion);
        if (regionObj) {
            setRegionName(languageMap[regionObj.textId]);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div className='actions'>
            <Dropdown
                arrow
                overlayClassName={`custom-dropdown ${
                    language.includes('zh') && platform === Platfrom.ALIBABA ? 'wider-dropdown' : ''
                }`}
                overlay={regionMenu}
                placement='bottomCenter'
                trigger={['click']}
            >
                <div className='region-selection'>
                    {regionName} <DownOutlined />
                </div>
            </Dropdown>

            <Popover
                arrowPointAtCenter
                trigger={['click']}
                placement='bottomRight'
                overlayClassName='menu-popover'
                visible={stageVisible}
                onVisibleChange={v => setStageVisible(v)}
                content={
                    <List
                        split={false}
                        size='small'
                        dataSource={stageOptions}
                        renderItem={item => (
                            <List.Item>
                                <div className='selection-item' onClick={() => onSelectedStage(item.value)}>
                                    <span>{item.text}</span>
                                    {stage === item.value && <TickIcon className='vscode-icon small-icon' />}
                                </div>
                            </List.Item>
                        )}
                    />
                }
            >
                <ServerIcon className='vscode-icon pointer' style={{ margin: '0 16px' }} />
            </Popover>

            <Popover
                trigger={['click']}
                placement='bottomRight'
                overlayClassName='menu-popover'
                arrowPointAtCenter
                visible={settingsVisible}
                onVisibleChange={v => setSettingsVisible(v)}
                title={
                    <>
                        <div className='account-label'>
                            <FormattedMessage id='info.settings.account' />
                        </div>
                        {deployInfo?.accountId}
                    </>
                }
                content={
                    <List split={false} size='small'>
                        {getPlatformMenu()}
                        <List.Item onClick={() => openLink(HelpDocumentLink.home)}>
                            <FormattedMessage id='info.settings.doc' />
                        </List.Item>
                        {!tencentOnly && (
                            <List.Item onClick={() => setStep(PageStep.HOME)}>
                                <FormattedMessage id='info.settings.switch' />
                            </List.Item>
                        )}
                        <List.Item onClick={logout}>
                            <FormattedMessage id='info.settings.logout' />
                        </List.Item>
                    </List>
                }
            >
                <SettingsIcon className='vscode-icon pointer' />
            </Popover>
        </div>
    );
};
