import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { SnackbarProvider, withSnackbar } from 'notistack';

import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';

import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions';
import Divider from '@material-ui/core/Divider';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import MenuItem from '@material-ui/core/MenuItem';
import Snackbar from '@material-ui/core/Snackbar';

import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import Switch from '@material-ui/core/Switch';

import CloseIcon from '@material-ui/icons/CloseOutlined';
import ReloadIcon from '@material-ui/icons/RefreshOutlined';
import ExpandLessIcon from '@material-ui/icons/ExpandLessOutlined';
import ExpandMoreIcon from '@material-ui/icons/ExpandMoreOutlined';

import NavigationBar from './Components/NavigationBar.jsx';

const styles = theme => ({
    button: {
        margin: theme.spacing(1),
    },
    heading: {
        fontSize: theme.typography.pxToRem(15),
        flexBasis: '33.33%',
        flexShrink: 0,
    },
    secondaryHeading: {
        fontSize: theme.typography.pxToRem(15)
    },
    formRoot: {
        display: 'flex',
        flexWrap: 'wrap',
    },
    formControl: {
        margin: theme.spacing.unit,
        minWidth: 120,
    },
    selectEmpty: {
        marginTop: theme.spacing.unit * 2,
    },
    snackBarClose: {
        padding: theme.spacing(0.5),
    },
});

class Settings extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isExpanded: null,
            isHomeButton: false,
            isBookmarkBar: false,
            isDarkTheme: false,
            isCustomTitlebar: false,
            isCustomTitlebar2: false,
            theme: 'default',
            searchEngine: 'None',
            searchEngines: [],
            isAdBlock: false,
            // Snackbar
            isShowingSnackbar: false,
            snackBarDuration: 4000,
            snackBarText: ''
        };
    }

    componentDidMount = () => {
        this.setState({
            isHomeButton: window.getHomeButton(),
            isBookmarkBar: window.getBookmarkBar(),
            isDarkTheme: window.getDarkTheme(),
            isCustomTitlebar: window.getCustomTitlebar(),
            isCustomTitlebar2: window.getCustomTitlebar(),
            searchEngine: window.getSearchEngine().name,
            isAdBlock: window.getAdBlock(),
        });


        window.getSearchEngines().forEach((item, i) => {
            this.setState(state => { return { searchEngines: [...state.searchEngines, item] }; });
        });
    }

    handleChange = (panel) => (e, isExpanded) => {
        this.setState({ isExpanded: isExpanded ? panel : false });
    };

    handleSnackbarClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }

        this.setState({ isShowingSnackbar: false });
    }

    render() {
        const { classes } = this.props;

        return (
            <NavigationBar title="設定" buttons={[<Button color="inherit" onClick={() => { window.openInEditor(); }}>テキストエディタで開く</Button>]}>
                <Container fixed>
                    <ExpansionPanel expanded={this.state.isExpanded === 'design'} onChange={this.handleChange('design')}>
                        <ExpansionPanelSummary
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="design-content"
                            id="design-header"
                        >
                            <Typography className={classes.heading}>デザイン</Typography>
                        </ExpansionPanelSummary>
                        <ExpansionPanelDetails>
                            <Grid container spacing={2}>
                                <Grid item xs={10} sm={11} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        ホームボタンを表示する
                                    </Typography>
                                </Grid>
                                <Grid item xs={2} sm={1} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <Switch
                                        checked={this.state.isHomeButton}
                                        onChange={(e) => {
                                            this.setState({ ...this.state, isHomeButton: e.target.checked });
                                            window.setHomeButton(e.target.checked);

                                            this.props.enqueueSnackbar('設定を変更しました。', {
                                                variant: 'success',
                                            });
                                        }}
                                        color="primary"
                                        value="isHomeButton"
                                    />
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={10} sm={11} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        ブックマーク バーを表示する
                                    </Typography>
                                </Grid>
                                <Grid item xs={2} sm={1} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <Switch
                                        checked={this.state.isBookmarkBar}
                                        onChange={(e) => {
                                            this.setState({ ...this.state, isBookmarkBar: e.target.checked });
                                            window.setBookmarkBar(e.target.checked);

                                            this.props.enqueueSnackbar('設定を変更しました。', {
                                                variant: 'success',
                                            });
                                        }}
                                        color="primary"
                                        value="isBookmarkBar"
                                    />
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={10} sm={11} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        ダーク テーマを使用する
                                    </Typography>
                                </Grid>
                                <Grid item xs={2} sm={1} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <Switch
                                        checked={this.state.isDarkTheme}
                                        onChange={(e) => {
                                            this.setState({ ...this.state, isDarkTheme: e.target.checked });
                                            window.setDarkTheme(e.target.checked);

                                            this.props.enqueueSnackbar('設定を変更しました。', {
                                                variant: 'success',
                                            });
                                        }}
                                        color="primary"
                                        value="isDarkTheme"
                                    />
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={8} sm={9} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        カスタムタイトルバーを使用する
                                    </Typography>
                                </Grid>
                                <Grid item xs={4} sm={3} style={{ display: 'flex', padding: '0px 8px' }} alignItems="center" justify="flex-end">
                                    {this.state.isCustomTitlebar2 !== window.getCustomTitlebar() ?
                                        <IconButton className={classes.button} onClick={() => { window.restart(); }}>
                                            <ReloadIcon />
                                        </IconButton>
                                        :
                                        null
                                    }
                                    <Switch
                                        checked={this.state.isCustomTitlebar}
                                        onChange={(e) => {
                                            this.setState({ ...this.state, isCustomTitlebar: e.target.checked });
                                            window.setCustomTitlebar(e.target.checked);

                                            this.props.enqueueSnackbar('設定を変更しました。', {
                                                variant: 'success',
                                            });
                                        }}
                                        color="primary"
                                        value="isCustomTitlebar"
                                    />
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={8} sm={8} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        ウィンドウの詳細設定
                                    </Typography>
                                </Grid>
                                <Grid item xs={4} sm={4} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <Button variant="outlined">変更</Button>
                                </Grid>
                            </Grid>
                        </ExpansionPanelDetails>
                    </ExpansionPanel>
                    <ExpansionPanel expanded={this.state.isExpanded === 'search'} onChange={this.handleChange('search')}>
                        <ExpansionPanelSummary
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="search-content"
                            id="search-header"
                        >
                            <Typography className={classes.heading}>検索エンジン</Typography>
                            <Typography color="textSecondary" className={classes.secondaryHeading}>現在、{window.getSearchEngine().name} を使用しています</Typography>
                        </ExpansionPanelSummary>
                        <ExpansionPanelDetails>
                            <Grid container spacing={2}>
                                <Grid item xs={8} sm={8} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        アドレスバーと<Link href="flast://credits/">新しいタブ</Link> ページで使用される検索エンジン
                                    </Typography>
                                </Grid>
                                <Grid item xs={4} sm={4} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <div className={classes.formRoot}>
                                        <FormControl className={classes.formControl}>
                                            <Select
                                                value={this.state.searchEngine}
                                                onChange={(e) => {
                                                    this.setState({ searchEngine: e.target.value });
                                                    window.setSearchEngine(e.target.value);

                                                    this.props.enqueueSnackbar('設定を変更しました。', {
                                                        variant: 'success',
                                                    });
                                                }}
                                                inputProps={{
                                                    name: 'searchEngine',
                                                    id: 'searchEngine',
                                                }}
                                            >
                                                {this.state.searchEngines.map((item, i) => {
                                                    return (
                                                        <MenuItem key={i} value={item.name}>{item.name}</MenuItem>
                                                    );
                                                })}
                                            </Select>
                                        </FormControl>
                                    </div>
                                </Grid>
                            </Grid>
                        </ExpansionPanelDetails>
                        <Divider />
                        <ExpansionPanelActions>
                            <Button variant="outlined" size="small">検索エンジンの管理</Button>
                        </ExpansionPanelActions>
                    </ExpansionPanel>
                    <ExpansionPanel expanded={this.state.isExpanded === 'adblock'} onChange={this.handleChange('adblock')}>
                        <ExpansionPanelSummary
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="adblock-content"
                            id="adblock-header"
                        >
                            <Typography className={classes.heading}>広告ブロック</Typography>
                            <Typography color="textSecondary" className={classes.secondaryHeading}>広告ブロックは{window.getAdBlock() ? '有効' : '無効'}です</Typography>
                        </ExpansionPanelSummary>
                        <ExpansionPanelDetails>
                            <Grid container spacing={2}>
                                <Grid item xs={10} sm={11} style={{ padding: '8px 14px' }}>
                                    <Typography variant="body2">
                                        広告ブロックを使用する
                                    </Typography>
                                </Grid>
                                <Grid item xs={2} sm={1} style={{ display: 'flex', padding: '0px 8px' }} direction="column" alignItems="flex-end">
                                    <Switch
                                        checked={this.state.isAdBlock}
                                        onChange={(e) => {
                                            this.setState({ ...this.state, isAdBlock: e.target.checked });
                                            window.setAdBlock(e.target.checked);

                                            this.props.enqueueSnackbar('設定を変更しました。', {
                                                variant: 'success',
                                            });
                                        }}
                                        color="primary"
                                        value="isAdBlock"
                                    />
                                </Grid>
                            </Grid>
                        </ExpansionPanelDetails>
                        <Divider />
                        <ExpansionPanelActions>
                            <Button variant="outlined" size="small"
                                onClick={() => {
                                    window.updateFilters();

                                    this.props.enqueueSnackbar('定義ファイルのアップデートと再読み込みをしています…', {
                                        variant: 'info',
                                    });
                                }}>定義ファイルのアップデート・再読み込み</Button>
                        </ExpansionPanelActions>
                    </ExpansionPanel>
                    <ExpansionPanel expanded={this.state.isExpanded === 'about'} onChange={this.handleChange('about')}>
                        <ExpansionPanelSummary
                            expandIcon={<ExpandMoreIcon />}
                            aria-controls="about-content"
                            id="about-header"
                        >
                            <Typography className={classes.heading}>{window.getAppName()} について</Typography>
                        </ExpansionPanelSummary>
                        <ExpansionPanelDetails>
                            <Grid container spacing={2}>
                                <Grid item style={{ width: 96, padding: '0px 16px' }}>
                                    <img src="flast-file:///icon.png" width="64" />
                                </Grid>
                                <Grid item style={{ display: 'flex', padding: '0px 16px' }} alignItems="center">
                                    <Typography variant="subtitle1" gutterBottom>{window.getAppName()}</Typography>
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={12} style={{ padding: '0px 16px' }}>
                                    <Typography variant="subtitle2" gutterBottom>{window.getAppName()} は(多分)最新版です</Typography>
                                    <Typography variant="body2" color="textSecondary" gutterBottom>
                                        バージョン: {window.getAppVersion()} ({window.getAppChannel()}) ({window.getChromiumVersion()})
                                    </Typography>
                                </Grid>
                                <Grid item xs={12}>
                                    <Divider />
                                </Grid>
                                <Grid item xs={12} style={{ padding: '0px 16px' }}>
                                    <Typography variant="body2" color="textSecondary" gutterBottom style={{ marginBottom: '0.8em' }}>
                                        {window.getAppName()}<br />
                                        {window.getAppDescription()}<br />
                                        Copyright 2019 Aoichaan0513. All rights reserved.
                                    </Typography>
                                    <Typography variant="body2" color="textSecondary" gutterBottom>
                                        {window.getAppName()} はChromiumやその他の<Link href="flast://credits/">オープンソース ソフトウェア</Link>によって実現しました。
                                    </Typography>
                                </Grid>
                            </Grid>
                        </ExpansionPanelDetails>
                        <Divider />
                        <ExpansionPanelActions>
                            <Button variant="outlined" size="small">リセット</Button>
                        </ExpansionPanelActions>
                    </ExpansionPanel>
                </Container>
            </NavigationBar>
        );
    }
}

Settings.propTypes = {
    classes: PropTypes.object.isRequired,
};

const Page = withSnackbar(withStyles(styles)(Settings));

render(
    <SnackbarProvider maxSnack={3} autoHideDuration={3000}>
        <Page />
    </SnackbarProvider>,
    document.getElementById('app')
);