import {
    Alert,
    AlertTitle,
    Card, CardActions,
    CardContent,
    CardHeader, Collapse,
    Grid, IconButton, IconButtonProps,
    Typography
} from '@mui/material';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import { styled } from '@mui/material/styles';
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import * as React from 'react';
import {EncryptStorage} from 'storage-encryption';
import {Delete} from "@mui/icons-material";
import MDEditor from "@uiw/react-md-editor";

interface Page {
    date: string;
    title: string;
    content: string;
}

interface ExpandMoreProps extends IconButtonProps {
    expand: boolean;
}

const ExpandMore = styled((props: ExpandMoreProps) => {
    const { expand, ...other } = props;
    return <IconButton {...other} />;
})(({ theme, expand }) => ({
    transform: !expand ? 'rotate(0deg)' : 'rotate(180deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
        duration: theme.transitions.duration.shortest,
    }),
}));

export default function Page({page, url, passphrase, setPassphrase, remove}) {
    const [more, setMore] = React.useState(false);
    const [expanded, setExpanded] = React.useState(false);
    const handleMoreClick = () => { setMore(!more); };
    const handleExpandClick = () => { onLoad().then(r => setExpanded(!expanded));  };

    const encryptStorage = new EncryptStorage(passphrase);
    let title, content = "";
    let alert_popup:JSX.Element|null = null;
    let setTitle, setContent: React.Dispatch<any>|null = null;
    let onLoad = async () => {};
    try {
        [content, setContent] = React.useState(encryptStorage.decrypt(page.id + "text"));
        [title, setTitle] = React.useState(encryptStorage.decrypt(page.id + "title"));
        onLoad = async () => {
            if (localStorage.getItem(page.id + "text") === null) {
                const response = await fetch(url.replace("replace_me", page.id));

                const json = await response.json();
                localStorage.setItem(page.id + "title", json.metadata.title);
                localStorage.setItem(page.id + "text", json.content);
            }
            setTitle(encryptStorage.decrypt(page.id + "title"));
            // @ts-ignore
            setContent(encryptStorage.decrypt(page.id + "text"));
        }
    } catch (e) {
        console.error(e);
        setPassphrase(null);
        alert_popup = <Alert severity="error">
            <AlertTitle>Erreur</AlertTitle>
            Vos pages ne peuvent pas être décodées — <strong>Réindiquez votre clef!</strong>
        </Alert>
    }

    return (
            <Grid item xs={12} sm={12} md={12} id={page.id}>
                {alert_popup}
                <Card>
                    <CardHeader
                        action={
                            <IconButton aria-label="settings" onClick={handleMoreClick}>
                                <MoreVertIcon />
                            </IconButton>
                        }
                        title={title}
                        subheader={page.date}
                    />
                    <Collapse in={more} timeout="auto" unmountOnExit>
                        <IconButton aria-label="remove" onClick={() => {remove(page.id)}} >
                            <Delete />
                        </IconButton>
                    </Collapse>
                    <CardActions disableSpacing>
                        <ExpandMore
                            expand={expanded}
                            onClick={handleExpandClick}
                            aria-expanded={expanded}
                            aria-label="show more"
                        >
                            <ExpandMoreIcon />
                        </ExpandMore>
                    </CardActions>
                    <Collapse in={expanded} timeout="auto" unmountOnExit>
                        <CardContent>
                            <Typography paragraph>
                                <MDEditor.Markdown source={content} />
                            </Typography>
                        </CardContent>
                    </Collapse>
                </Card>
            </Grid>
    );
}
