import React, {Component} from "react";
import {
    Backdrop,
    Box,
    Button,
    Chip,
    CircularProgress,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    Fade,
    FormControl,
    Modal,
    Snackbar,
    Stack,
    Typography, Zoom
} from "@mui/material";
import {FunctionTest} from "../RawConstants";
import SettingsIcon from '@mui/icons-material/Settings';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import CloudOffIcon from '@mui/icons-material/CloudOff';
import CloudIcon from '@mui/icons-material/Cloud';
import {PAGE} from "./App";
import GameHandler from "./GameHandler";

interface StartupProps {
    visible: boolean
}

interface StartupState {
    statusTxt: string,
    openCloudConnectModal: boolean,
    showStartBtn: boolean,
    isCloudConnected: boolean,
    snackErrorMsg: string,
    isConnectionIssue: boolean,
    startCounter: number,
}

export default class Startup extends Component<StartupProps, StartupState> {
    constructor(props: StartupProps) {
        super(props);
        this.state = {
            statusTxt: "Smart-Monopoly wird gestartet...",
            openCloudConnectModal: false,
            showStartBtn: false,
            isCloudConnected: false,
            isConnectionIssue: false,
            snackErrorMsg: "",
            startCounter: 10,
        };
    }

    counterInterval: string | number | NodeJS.Timeout;

    componentDidMount() {
        setTimeout(() => {
            this.setState((prevState) => ({
                ...prevState,
                openCloudConnectModal: true,
                statusTxt: "Möchten Sie CloudConnect+ nutzen?"
            }));
        }, 1)
    }

    componentWillUnmount() {

    }

    connectToCloud = async (): Promise<boolean> => {
        try {
            let response = await window.api.request("CLOUD_CONNECT", {});
            this.setState((prevState) => ({
                ...prevState,
                snackErrorMsg: response.data.toString(),
                isCloudConnected: response.status,
                isConnectionIssue: !response.status,
            }));
            console.log(response)
            return response.status;
        } catch (e) {
            return false;
        }
    }

    startupBtnClick = () => {
        // Startup handle
        this.setState(prevState => ({
            ...prevState,
            showStartBtn: false,
            statusTxt: "Kapitalismus an die Macht!"
        }));
        setTimeout(async () => {
            try {
                let resp = await GameHandler.requestPreparing(this.state.isCloudConnected);
            } catch(e)
            {
                this.setState(prevState => ({
                    ...prevState,
                    showStartBtn: true,
                    snackErrorMsg: "Start fehlgeschlagen! \n" + e.toString()
                }));
                await this.cloudDecision(false);
            }
        }, 1500)



    }

    style = {
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 600,
        bgcolor: 'background.paper',
        border: '2px solid #0000',
        boxShadow: 24,
        p: 4,
    };


    async cloudDecision(decision: boolean) {
        this.setState((prevState) => ({
            ...prevState,
            openCloudConnectModal: false,
            isConnectionIssue: false,
            isCloudConnected: false,
            startCounter: 30
        }));
        clearInterval(this.counterInterval);


        if (decision) {
            this.setState((prevState) => ({
                ...prevState,
                statusTxt: "Internetverbindung wird geprüft..."
            }));

            let status = (await window.api.request("FUNCTION_TEST", {})).data as FunctionTest;
            if (!status.hasInternet) {
                this.setState((prevState) => ({
                    ...prevState,
                    isConnectionIssue: true, // Weiterleiten auf Fehlermodal
                    statusTxt: "Warten auf Netzwerk..."
                }));
            } else {
                this.setState((prevState) => ({
                    ...prevState,
                    statusTxt: "Warten auf Cloud...",
                }));

                this.connectToCloud().then((connected) => {
                    this.setState((prevState) => ({
                            ...prevState,
                            statusTxt: "Bereit zum Spielen?",
                            showStartBtn: true,
                        })
                    )
                    if (connected)
                        this.counterInterval = setInterval(() => {
                            if (!this.props.visible) return;
                            if (this.state.startCounter == 0) {
                                clearInterval(this.counterInterval);
                                this.startupBtnClick();
                                return;
                            }
                            this.setState((prevState) => ({
                                ...prevState,
                                startCounter: prevState.startCounter - 1
                            }));

                        }, 1000);
                });
            }
        } else {
            this.setState((prevState) => ({
                ...prevState,
                statusTxt: "Bereit zum Spielen?",
                showStartBtn: true,
                startCounter: 30
            }));
            this.counterInterval = setInterval(() => {
                if (!this.props.visible) return;

                if (this.state.startCounter == 0) {
                    clearInterval(this.counterInterval);
                    this.startupBtnClick();
                    return;
                }
                this.setState((prevState) => ({
                    ...prevState,
                    startCounter: prevState.startCounter - 1
                }));

            }, 1000);
        }

    }

    render() {
        return <div className={`startup ${this.props.visible ? '' : 'hidden'}`}>
            <Snackbar
                open={this.state.snackErrorMsg != ""}
                autoHideDuration={8000}
                onClose={() => {
                    this.setState(prevState => ({
                        ...prevState,
                        snackErrorMsg: ""
                    }))
                }}
                message={this.state.snackErrorMsg}
            />
            <Dialog
                open={this.state.isConnectionIssue}
                onClose={null}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
            >
                <DialogTitle id="alert-dialog-title">
                    Cloud-Verbindung fehlgeschlagen!
                </DialogTitle>
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        Die Cloud-Verbindung konnte nicht hergestellt werden.<br/>
                        Möglicherweise liegt ein Problem mit der Internetverbindung vor,<br/>
                        oder die Cloud ist derzeit in Wartung.<br/>
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => this.cloudDecision(false)}>
                        Offline spielen
                    </Button>
                    <Button onClick={() =>
                        window.app.toggleWiFiSettings(true)} autoFocus>WiFi-Einstellungen</Button>
                    <Button onClick={() => this.cloudDecision(true)} autoFocus>Erneut versuchen</Button>
                </DialogActions>
            </Dialog>

            <Modal
                aria-labelledby="transition-modal-title"
                aria-describedby="transition-modal-description"
                open={this.state.openCloudConnectModal}
                onClose={null}
                closeAfterTransition
                slots={{backdrop: Backdrop}}
                slotProps={{
                    backdrop: {
                        timeout: 500,
                    },
                }}
            >
                <Fade in={this.state.openCloudConnectModal}>
                    <Box sx={this.style}>
                        <Typography id="transition-modal-title" variant="h6" component="h2">
                            CloudConnect+ nutzen?
                        </Typography>
                        <Typography id="transition-modal-description" sx={{mt: 2}}>
                            Möchten Sie für diese Sitzung CloudConnect+ aktivieren, um das mitspielen mit Mobilen
                            Endgeräten zu ermöglichen?
                            <br/>
                            <i>Dafür wird eine WiFi-Verbindung hergestellt</i>
                            <br/>
                            <br/>
                            <Button variant="contained" sx={{mr: 1}}
                                    onClick={() => this.cloudDecision(true)}>Ja</Button>
                            <Button variant="contained" onClick={() => this.cloudDecision(false)}
                                    color="error">Nein</Button>
                        </Typography>
                    </Box>
                </Fade>
            </Modal>

            <Stack className="centerMiddle" alignItems="center">
                <h1>Willkommen!</h1>
                <br/>
                <p>{this.state.statusTxt}</p>
                <br/>
                {!this.state.showStartBtn && <CircularProgress/>}

                <Box alignItems="center" sx={{width: '100%'}}>
                    <FormControl sx={{mr: 2, minWidth: '30%'}}>
                        <Zoom in={this.state.showStartBtn}><Button color="secondary"
                                                                   onClick={() => window.app.setPage(PAGE.SETUP)}
                                                                   variant="contained">Einstellungen <SettingsIcon/></Button></Zoom>
                    </FormControl>
                    <FormControl sx={{minWidth: '30%'}}>
                        <Zoom in={this.state.showStartBtn}><Button color="success"
                                                                   onClick={() => this.startupBtnClick()}
                                                                   variant="contained">Start <Chip sx={{ml: 1}}
                                                                                                   size="small"
                                                                                                   label={this.state.startCounter}/>
                            <PlayCircleIcon/></Button></Zoom>
                    </FormControl>
                </Box>
                <Chip sx={{mt: 3}} color={this.state.isCloudConnected ? "success" : "default"}
                      disabled={!this.state.showStartBtn} onClick={() => this.setState(prevState => ({
                    ...prevState,
                    openCloudConnectModal: true
                }))} label={this.state.isCloudConnected ? <CloudIcon/> : <CloudOffIcon/>}/>

            </Stack>
        </div>

    }

}