import React, {useEffect, useState} from "react";
import axios from "axios";
import {__} from '@wordpress/i18n';
import Alert from "@mui/material/Alert";
import Card from "@mui/material/Card";
import CircularProgress from '@mui/material/CircularProgress';
import Snackbar from '@mui/material/Snackbar';
import Stack from '@mui/material/Stack';
import {Accordion, AccordionActions, AccordionDetails, AccordionSummary, Button, ButtonGroup} from "@mui/material";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import StyleCard from "@components/style/StyleCard";

interface LocatorStylesProps {
    activateStyle: (styleId: number, styleName: string) => Promise<{ message: string; severity: string }>;
    activeStyleID: number;
    setActiveStyleID: (styleId: number) => void;
}

/**
 * Location Search Report Card
 * @returns {JSX.Element}
 * @constructor
 */
const LocatorStyles: React.FC<LocatorStylesProps> = ({activateStyle, activeStyleID, setActiveStyleID}): JSX.Element => {
    const [listOrderBy, setListOrderBy] = useState<string>('title');
    const [listOrderDirection, setListOrderDirection] = useState<string>('asc');
    const [sbOpen, setSBOpen] = useState<boolean>(false); // Alerts open/close handler
    const [sbMsg, setSBMsg] = useState<string>(''); // Alerts message
    const [data, setData] = useState<any[]>([]); // rest API response records

    /**
     * Snackbar message close handler
     * @param event
     * @param reason
     */
    const handleClose = () => {
        setSBMsg('');
        setSBOpen(false);
    };

    /**
     * Get the styles from the style server.
     */
    useEffect(() => {
        function getData() {
            const fields = 'id,slug,title,modified,featured_media,content,yoast_head_json.og_image';

            // -- async fetch search history
            axios.get(`${slpReact.url.main_site}/wp-json/wp/v2/slp_style_gallery/?orderby=${listOrderBy}&order=${listOrderDirection}&per_page=100&_fields=${fields}`)
                // -- response received
                // .data is the body of the response
                .then((response) => {

                    // if status code is not 200, something is wrong
                    if (response.status !== 200) {
                        throw new Error(response.data);
                    }
                    setData(response.data);
                })

                // -- something broke
                .catch((error) => {
                    setSBMsg(__('Could not retrieve locator styles list.', 'store-locator-le'));
                    console.log('Style list retrieval issue',error);
                    setSBOpen(true);
                });

        }

        getData();
    }, [listOrderBy]);

    /**
     * Render
     */
    return (
        <>
            <Snackbar
                open={sbOpen}
                anchorOrigin={{vertical: 'top', horizontal: 'center'}}
                autoHideDuration={3000}
                onClose={handleClose}
            >
                <Alert onClose={handleClose} severity="warning" sx={{width: '100%'}}>
                    {sbMsg}
                </Alert>
            </Snackbar>
            <div
                className="styleList"
                style={{
                    maxHeight: '100vh', // Prevent the div from exceeding the viewport height
                    overflowY: 'auto',  // Enable scrolling for the content
                }}
            >
                <Accordion defaultExpanded>
                    <AccordionSummary
                        expandIcon={<ExpandMoreIcon />}
                        aria-controls="panel-stylelist-content"
                        id="panel-stylelist-header"
                    >
                        {__('Locator Styles', 'store-locator-le')}
                    </AccordionSummary>
                    <AccordionActions>
                        <ButtonGroup color="primary" size="small" variant="outlined">
                            <Button key="bytitle" onClick={() => { setListOrderDirection('asc'); setListOrderBy('title'); } }>a..z</Button>
                            <Button key="bydate" onClick={() => { setListOrderDirection('desc'); setListOrderBy('modified'); }}>new..old</Button>
                        </ButtonGroup>
                    </AccordionActions>
                    <AccordionDetails>
                        <Stack spacing={1}>
                            {
                                data.length ? data.map((post) => (
                                        <StyleCard
                                            key={post.id}
                                            post={post}
                                            activateStyle={activateStyle}
                                            activeStyleID={activeStyleID}
                                            setActiveStyleID={setActiveStyleID}
                                        />
                                    )) :
                                    (
                                        <Card sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', padding: 10 }}>
                                            <CircularProgress />
                                        </Card>
                                    )
                            }
                        </Stack>
                    </AccordionDetails>
                </Accordion>
            </div>
        </>
    )
        ;
}

export default LocatorStyles;