import { AppBar, createStyles, makeStyles, styled, Tab, Tabs, Theme, withStyles } from '@material-ui/core';
import * as React from 'react'
import { tabA11yProps, TabPanel, toMenuItems } from './FormUtil';
import * as _m from '../models/Manifest'
import { FormikTextField } from '../components/common/FormikTextField';
import { FormikCardList } from '../components/common/FormikCardList';
import NotConfigured from './NotConfiguredPanel';
import { useField, useFormikContext } from 'formik';

const useStyles = makeStyles((theme: Theme) => ({
    root: {
        flexGrow: 1,
        backgroundColor: theme.palette.background.paper,
    },
    alertPanel: {
        width: 1200
    },
}));

const alertTypes = {
    'loadBalancer': ['http4xx', 'http5xx', 'elb4xx', 'elb5xx', 'latency'],
    'database': ['highActiveConnection', 'connectionAcquireTimeIsHigh', 'maxConnectionPoolReached'],
    'kafka': ['consumerGroupLag', 'kafkaMessageRate']
}

const severity = ['critical', 'warning']

const FixWidthTextField = styled(FormikTextField)({
    margin: 5,
    width: 300
})

interface StyledTabProps {
    label: string;
}

const commonAlerts = (i, alertType) => (<>
    <FixWidthTextField select label="Type" name={`deployment.alerts.${alertType}.${i}.type`} >
        {toMenuItems(alertTypes[alertType])}
    </FixWidthTextField>
    <FixWidthTextField select label="Severity" name={`deployment.alerts.${alertType}.${i}.severity`} >
        {toMenuItems(severity)}
    </FixWidthTextField>
    <FixWidthTextField label="Threshold" name={`deployment.alerts.${alertType}.${i}.threshold`} />
    <FixWidthTextField label="Duration" name={`deployment.alerts.${alertType}.${i}.duration`} />
</>
)

const LoadBalancerAlert = () => {
    const alertType = 'loadBalancer'
    return (
        <FormikCardList newItem={_m.newLoadBalancerAlert} name={`deployment.alerts.${alertType}`} newItemLabel="Add LoadBalancer Alert">
            {(i) => commonAlerts(i, alertType)}
        </FormikCardList>
    )
}

const DatabaseAlert = () => {
    const alertType = 'database'
    return (
        <FormikCardList newItem={_m.newDatabaseAlert} name={`deployment.alerts.${alertType}`} newItemLabel="Add Database Alert">
            {(i) => commonAlerts(i, alertType)}
        </FormikCardList>
    )
}

const KafkaAlertGroupField = (props) => {
    const { i } = props
    const [kafkaAlertType] = useField(`deployment.alerts.kafka.${i}.type`)
    if (kafkaAlertType.value === "consumerGroupLag") {
        return <FixWidthTextField label="Group" name={`deployment.alerts.kafka.${i}.group`} />
    } else {
        return <></>
    }
}

const KafkaAlert = () => {
    const alertType = 'kafka'
    return (
        <FormikCardList newItem={_m.newKafkaAlert} name={`deployment.alerts.${alertType}`} newItemLabel="Add Kafka Alert">
            {(i) => (<>
                {commonAlerts(i, alertType)}
                <FixWidthTextField label="Topic" name={`deployment.alerts.${alertType}.${i}.topic`} />
                <KafkaAlertGroupField i={i} />
            </>)}
        </FormikCardList>
    )
}

const CustomAlert = () => {
    const alertType = 'custom'
    return (
        <FormikCardList newItem={_m.newCustomAlert} name={`deployment.alerts.${alertType}`} newItemLabel="Add Custom Alert">
            {(i) => (<>
                <FixWidthTextField label="Name" name={`deployment.alerts.${alertType}.${i}.name`} />
                <FixWidthTextField label="Description" name={`deployment.alerts.${alertType}.${i}.description`} />
                <FixWidthTextField label="Summary" name={`deployment.alerts.${alertType}.${i}.summary`} />
                <FixWidthTextField label="Duration" name={`deployment.alerts.${alertType}.${i}.duration`} />
                <FixWidthTextField label="Expression" name={`deployment.alerts.${alertType}.${i}.expression`} />
                <FixWidthTextField select label="Severity" name={`deployment.alerts.${alertType}.${i}.severity`}>
                    {toMenuItems(severity)}
                </FixWidthTextField>
            </>)}
        </FormikCardList>
    )
}

const AlertForm = () => {
    const classes = useStyles();
    const { values, setValues }: { values: any, setValues: any } = useFormikContext()
    const [currentTab, setCurrentTab] = React.useState(0);

    const handleTabChange = (event: React.ChangeEvent<{}>, newTab: number) => {
        setCurrentTab(newTab);
    };

    return (
        <NotConfigured
            name="Alerts"
            addRemoveCondition={_m.hasAlerts(values)}
            addAction={() => setValues(_m.addAlerts(values))}
            removeAction={() => setValues(_m.removeAlerts(values))} >

            <div className={classes.root}>
                <AppBar position="static" color="transparent" variant="outlined">
                    <Tabs value={currentTab} onChange={handleTabChange}>
                        <Tab label="LoadBalancer" {...tabA11yProps(0, 'simple')} />
                        <Tab label="Database" {...tabA11yProps(1, 'simple')} />
                        <Tab label="Kafka" {...tabA11yProps(2, 'simple')} />
                        <Tab label="Custom" {...tabA11yProps(3, 'simple')} />
                    </Tabs>
                </AppBar>
                <TabPanel value={currentTab} index={0} tabtype='simple'>
                    <div className={classes.alertPanel}><LoadBalancerAlert /></div>
                </TabPanel>
                <TabPanel value={currentTab} index={1} tabtype='simple'>
                    <div className={classes.alertPanel}><DatabaseAlert /></div>
                </TabPanel>
                <TabPanel value={currentTab} index={2} tabtype='simple'>
                    <div className={classes.alertPanel}><KafkaAlert /></div>
                </TabPanel>
                <TabPanel value={currentTab} index={3} tabtype='simple'>
                    <div className={classes.alertPanel}><CustomAlert /></div>
                </TabPanel>
            </div>
        </NotConfigured>
    )
}
export default AlertForm