import React, { useEffect, useState, useCallback } from "react";
import {
    Box,
    Button,
    createTheme,
    CssBaseline,
    Grid,
    OutlinedInput,
    ThemeProvider,
    Typography,
    ToggleButton,
    ToggleButtonGroup
} from "@mui/material";
import LightModeIcon from "@mui/icons-material/LightMode";
import DarkModeIcon from "@mui/icons-material/DarkMode";
import SettingsBrightnessIcon from "@mui/icons-material/SettingsBrightness";
import { ipc } from "./gen/ipc";

const App = () => {
    const [themeMode, setThemeMode] = useState(() => {
        return localStorage.getItem("theme") || "system";
    });

    const [systemDark, setSystemDark] = useState(
        window.matchMedia("(prefers-color-scheme: dark)").matches
    );

    useEffect(() => {
        const mq = window.matchMedia("(prefers-color-scheme: dark)");
        const handler = (e) => setSystemDark(e.matches);
        mq.addEventListener("change", handler);
        return () => mq.removeEventListener("change", handler);
    }, []);

    const isDark = themeMode === "dark" || (themeMode === "system" && systemDark);

    const theme = React.useMemo(
        () =>
            createTheme({
                palette: {
                    mode: isDark ? "dark" : "light",
                },
            }),
        [isDark]
    );

    const setAppTheme = useCallback((val) => {
        if (!val) return;
        ipc.app.SetTheme({ theme: val }).then(() => {
            localStorage.setItem("theme", val);
            setThemeMode(val);
        });
    }, []);

    const animationStyle = (delayMs) => ({ animationDelay: `${delayMs}ms` });

    const sayHello = () => {
        const name = document.querySelector("#greet-input").value;
        ipc.greet.SayHello({ name: name }).then((message) =>
            document.querySelector("#greet-msg").textContent = message.value
        );
    };

    const handleKeyPress = (event) => {
        if (event.key === "Enter") {
            document.querySelector("#greet-btn").click();
        }
    };

    return (
        <ThemeProvider theme={theme}>
            <CssBaseline/>
            <Grid container direction="column" textAlign="center" style={{marginTop: 128}}>
                <Grid item className="show-animation" style={animationStyle(0)}>
                    <img src="/logo.svg" alt="MōBrowser logo" style={{height: "128px"}}/>
                </Grid>
                <Grid item className="show-animation" style={{margin: 27, ...animationStyle(80)}}>
                    <Typography variant="h3" fontSize={"2.5rem"} fontWeight={"bold"}>
                        Welcome to MōBrowser!
                    </Typography>
                </Grid>
                <Grid item className="show-animation" style={{margin: 16, ...animationStyle(160)}}>
                    <Typography variant="body1">Please enter your name and click the button.</Typography>
                </Grid>
                <Grid item className="show-animation" style={animationStyle(240)}>
                    <Box display="flex" justifyContent="center" height={38}>
                        <OutlinedInput
                            id="greet-input"
                            placeholder="Your name"
                            sx={{
                                height: "100%",
                            }}
                            onKeyDown={handleKeyPress}
                        />
                        <Button
                            id="greet-btn"
                            variant="contained"
                            onClick={sayHello}
                            size="medium"
                            sx={{
                                height: "100%",
                                marginLeft: "8px",
                                textTransform: "none"
                            }}
                        >
                            Greet
                        </Button>
                    </Box>
                </Grid>
                <Grid item className="show-animation" style={{marginTop: 16, ...animationStyle(320)}}>
                    <Typography id="greet-msg"></Typography>
                </Grid>
                <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 100 }}>
                    <div className="show-animation" style={animationStyle(400)}>
                        <Box sx={(theme) => ({
                            bgcolor: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.08)' : 'background.paper',
                            borderRadius: '100px',
                            p: '4px',
                            border: `1px solid ${theme.palette.divider}`,
                            boxShadow: theme.palette.mode === 'dark' ? 'none' : 1,
                            display: 'flex',
                            position: 'relative'
                        })}>
                            <Box 
                                sx={(theme) => ({
                                    position: 'absolute',
                                    left: '4px',
                                    top: '4px',
                                    bottom: '4px',
                                    width: '36px',
                                    borderRadius: '100px',
                                    backgroundColor: theme.palette.mode === 'dark' ? 'rgba(255, 255, 255, 0.12)' : 'rgba(0, 0, 0, 0.08)',
                                    transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                    transform: themeMode === 'light' ? 'translateX(0)' : themeMode === 'system' ? 'translateX(36px)' : 'translateX(72px)',
                                    zIndex: 0,
                                    pointerEvents: 'none'
                                })}
                            />
                            <ToggleButtonGroup
                                value={themeMode}
                                exclusive
                                onChange={(_, val) => setAppTheme(val)}
                                size="small"
                                sx={{
                                    zIndex: 1,
                                    gap: 0,
                                    '& .MuiToggleButton-root': {
                                        margin: '0 !important',
                                        border: 'none',
                                        borderRadius: '100px !important',
                                        width: '36px',
                                        height: '24px',
                                        padding: 0,
                                        color: 'text.secondary',
                                        '&.Mui-selected': {
                                            backgroundColor: 'transparent !important',
                                            color: 'text.primary',
                                        },
                                        '&:hover': {
                                            backgroundColor: 'transparent',
                                            color: 'text.primary',
                                        }
                                    }
                                }}
                            >
                                <ToggleButton value="light" aria-label="light theme" disableRipple>
                                    <LightModeIcon sx={{ fontSize: 18 }} />
                                </ToggleButton>
                                <ToggleButton value="system" aria-label="system theme" disableRipple>
                                    <SettingsBrightnessIcon sx={{ fontSize: 18 }} />
                                </ToggleButton>
                                <ToggleButton value="dark" aria-label="dark theme" disableRipple>
                                    <DarkModeIcon sx={{ fontSize: 18 }} />
                                </ToggleButton>
                            </ToggleButtonGroup>
                        </Box>
                    </div>
                </div>
                {window.navigator.userAgent.indexOf("Mac") !== -1 && (<div className="draggable"></div>)}
            </Grid>
        </ThemeProvider>
    );
};

export default App;
