import {useEffect, useState} from "react";
import '../assets/styles/home.css';
import {
    Divider,
    TextField,
    ThemeProvider,
    useTheme
} from "@mui/material";
import {getAll} from '~/api';
import customTheme from "~/assets/mui/themes/home";
import {BlacklistItem} from "~/classes/blacklistItem";
import {ResponseError} from "~/classes/responseError";
import ItemList from "~/components/itemList";
import ItemDialog from "~/components/itemDialog";

export default function Home() {
    const outerTheme = useTheme();

    const [searchText, setSearchText] = useState('');
    const [isFetchingList, setIsFetchingList] = useState(false);
    const [blacklistItems, setBlacklistItems] = useState<BlacklistItem[]>([]);
    const [showDialog, setShowDialog] = useState(false);
    const [currentDialogBlacklistItem, setCurrentDialogBlacklistItem] = useState<BlacklistItem|null>(null);

    useEffect(() => {
        let isIgnore = false;
        setIsFetchingList(true);
        getAll(searchText).then((res: BlacklistItem[] | ResponseError | undefined)=> {
            if (!isIgnore) {
                if (res instanceof Array){
                    setBlacklistItems(res);
                } else if (res instanceof ResponseError) {
                    // TODO error handler
                    console.log(res);
                }
                setIsFetchingList(false);
            }
        });
        return () => {
            isIgnore = true; // При следующем изменении someValue старый запрос будет проигнорирован
        };
    }, [searchText]);

    function handleSearch(text: string) {
        setSearchText(text);
    }

    function handleItemClick(item: BlacklistItem){
        setCurrentDialogBlacklistItem(item);
        console.log(item);
        setShowDialog(true);
    }

    const handleDialogClose = () => {
        setShowDialog(false);
    };

    return (
        <ThemeProvider theme={customTheme(outerTheme)}>
            <div className="bg-dark">
                <div className="search-container">
                    <TextField
                        id="search-field"
                        label="Search"
                        variant="outlined"
                        value={searchText}
                        onChange={(e) => handleSearch(e.target.value)}
                        fullWidth
                    />
                </div>
                <div style={{justifyItems: 'center'}}>
                    <Divider sx={{marginTop: '10px', marginBottom: '10px'}}/>
                </div>
                <ItemList isFetching={isFetchingList} blacklistItems={blacklistItems} showDialog={handleItemClick}></ItemList>
                <ItemDialog blacklistItem={currentDialogBlacklistItem} open={showDialog} handleClose={handleDialogClose}></ItemDialog>
            </div>
        </ThemeProvider>
    );
}
