import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import * as React from "react";
import {useEffect, useState} from "react";
import Paper from "@mui/material/Paper";
import {Autocomplete} from "@mui/material";
import TextField from "@mui/material/TextField";
import {api} from "../../../lib/clients/api";
import {requests} from "../../../requests";
import {useAlert} from "../../../hooks/useAlert";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import CheckMarks from "../../../components/cocktails/CheckMarks";
import {EditCocktailReceipt} from "../../../components/cocktails/EditCocktailReceipt";
import {SelectEdit} from "../../../components/cocktails/SelectEdit";
import {getComparator} from "../../../components/core/getComparator";
import {useSearchParams} from "react-router-dom";
import {Loading} from "../../../components/core/Loading";
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import {styled} from "@mui/material/styles";

const emptyCocktail = {
    id: null,
    name: "",
    alcoholic: "",
    category: "",
    components: "",
    glass: "",
    image: "",
    instructions: "",
    isAllowed: false,
    rating: {
        rating: 0,
        favourite: false
    },
    receipt: [],
    tags: "",
    video: ""
};
const alcohol = [
    {
        id: 1,
        name: "Алкогольный"
    },
    {
        id: 2,
        name: "Безалкогольный",
    },
    {
        id: 3,
        name: "Опционально"
    }
]
const VisuallyHiddenInput = styled('input')({
    clip: 'rect(0 0 0 0)',
    clipPath: 'inset(50%)',
    height: 1,
    overflow: 'hidden',
    position: 'absolute',
    bottom: 0,
    left: 0,
    whiteSpace: 'nowrap',
    width: 1,
});

export function EditCocktailPage() {
    const [searchParams] = useSearchParams();
    const [loading, setLoading] = useState(true);
    const {createError, createSuccess, getError} = useAlert();
    const [cocktails, setCocktails] = useState([]);
    const [selected, setSelected] = useState(null);
    const [cocktail, setCocktail] = useState(emptyCocktail);

    const [glass, setGlass] = useState([]);
    const [category, setCategory] = useState([]);
    const [tags, setTags] = useState([])

    useEffect(() => {
        api().get(requests.cocktails.simple)
            .then((r) => {
                const arr = r.data.sort(getComparator("asc", "name"));
                setCocktails(arr)

                const currentId = searchParams.get("id");
                if (!currentId) {
                    setLoading(false);
                    return;
                }
                const currentCocktail = arr.find((r) => r.id === (currentId * 1));
                if (!currentCocktail) {
                    setLoading(false);
                    return;
                }
                setSelected(currentCocktail.id);
                setLoading(false);
            })
            .catch(() => createError("Ошибка получения данных"))

        api().get(requests.bar.category)
            .then((r) => setCategory(r.data.sort(getComparator("asc", "name"))))
            .catch(() => createError("Ошибка получения категорий"))

        api().get(requests.bar.glass)
            .then((r) => setGlass(r.data.sort(getComparator("asc", "name"))))
            .catch(() => createError("Ошибка получения посуды"))

        api().get(requests.bar.tags)
            .then((r) => setTags(r.data.sort(getComparator("asc", "name"))))
            .catch(() => createError("Ошибка получения тегов"))
        // eslint-disable-next-line
    }, []);
    useEffect(() => {
        if (!selected) {
            setCocktail(emptyCocktail);
            return;
        }
        api().get(requests.cocktails.cocktail + selected)
            .then((r) => {
                setCocktail(r.data)
            })
            .catch(() => getError());
        // eslint-disable-next-line
    }, [selected])

    const changeCocktailValue = (name, value) => {
        if (name === "tags") {
            value = value.join(",");
        }
        setCocktail((prev) => ({
            ...prev,
            [name]: value
        }))
    }
    const saveHandler = () => {
        api().patch(requests.cocktails.edit, cocktail)
            .then((r) => {
                if (!r.data.error) {
                    createSuccess("Сохранено")
                    return;
                }
                createError("Ошибка на сервере: " + r.data.error)
            })
            .catch(() => createError("Неизвестная ошибка"))
    }
    const deleteHandle = () => {
        api().delete(requests.cocktails.cocktail + cocktail.id)
            .then(() => {
                setCocktails(cocktails.filter((r) => r.id !== cocktail.id))
                setCocktail(emptyCocktail);
            })
            .catch(() => createError("Ошибка удаления коктейля"))
    }
    return (
        <Box>
            {/*Загрузка*/}
            <Loading loading={loading}/>
            {/*Заголовок*/}
            <Toolbar>
                <Typography variant="h6" component="div" sx={{flexGrow: 1}}>Коктейли</Typography>
            </Toolbar>
            {/*Поиск*/}
            <Paper elevation={6} sx={{my: 2, display: 'grid', p: 2}}>
                <Autocomplete
                    disablePortal
                    options={cocktails}
                    onChange={(e, v) => {
                        if (!v) {
                            setCocktail(emptyCocktail);
                            setSelected(null)
                        } else {
                            setSelected(v.id)
                        }
                    }}
                    isOptionEqualToValue={(selected, value) => selected.id === value.id}
                    getOptionKey={(selected) => selected.id}
                    getOptionLabel={(selected) => selected.name + (selected.hasError ? " (есть ошибка)" : "")}
                    renderInput={(params) => <TextField {...params} label="Поиск"/>}
                />
            </Paper>
            {/*Рабочая область*/}
            <Paper elevation={6} sx={{my: 2, display: 'grid', p: 1, pb: 2}}>
                <Stack>
                    <Box hidden={cocktail.id === null} ml={1} mb={1}>
                        <Button color='error' onClick={() => deleteHandle()}>Удалить коктейль</Button>
                    </Box>
                    {/*Фото*/}
                    <Box ml={1}>
                        <img src={cocktail.image} alt={""} width={300} height={300} loading={'eager'}/>
                    </Box>
                    {/*Редактирование ссылки на фото*/}
                    <Stack direction='row' pr={2} m={1} display='relative'>
                        <TextField sx={{width: '75%'}}
                                   label={"Ссылка на фото"} variant='outlined' multiline
                                   value={!cocktail.image ? "" : cocktail.image}
                                   onChange={(e) => changeCocktailValue("image", e.target.value)}
                        />
                        <Button
                            component="label"
                            role={undefined}
                            variant="contained"
                            tabIndex={-1}
                            startIcon={<CloudUploadIcon/>}
                            sx={{width: '10%', fontSize: 40, ml: 1, pr: 1}}
                        >
                            <VisuallyHiddenInput
                                type="file"
                                accept=".jpg,.jpeg,.png"
                                onChange={(event) => {
                                    const file = event.target.files[0];
                                    let formData = new FormData();
                                    formData.append('file', file);
                                    api().post(requests.cocktails.savePhoto, formData)
                                        .then((r) => changeCocktailValue("image", r.data))
                                        .catch(() => getError())
                                }}
                            />
                        </Button>

                    </Stack>
                    {/*Название*/}
                    <Box m={1}>
                        <TextField sx={{mr: 1, mb: 2, minWidth: 300}}
                                   variant="outlined" label={"Название"}
                                   value={cocktail.name}
                                   onChange={(e) => changeCocktailValue("name", e.target.value)}/>
                    </Box>
                    {/*Категория, посуда, алкогольность, теги*/}
                    <Box mb={2}>
                        <SelectEdit value={cocktail.category} label={"Категория"} width={300} margin={1}
                                    array={category}
                                    attributeName={"category"} handler={changeCocktailValue}/>
                        <SelectEdit value={cocktail.glass} label={"Посуда"} width={300} margin={1} array={glass}
                                    attributeName={"glass"} handler={changeCocktailValue}/>
                        <SelectEdit value={cocktail.alcoholic} label={"Алкогольность"} width={300} margin={1}
                                    array={alcohol}
                                    attributeName={"alcoholic"} handler={changeCocktailValue}/>
                        <CheckMarks rows={tags} width={300} name={"Теги"} handleChange={changeCocktailValue}
                                    filterValue={cocktail.tags.split(",")} filterName={"tags"}/>
                    </Box>
                    {/*Рецепт*/}
                    <EditCocktailReceipt receipt={cocktail.receipt} handler={changeCocktailValue}/>

                    <Box pr={2} ml={1}>
                        <TextField sx={{width: '100%'}}
                                   label={"Инструкция"} variant='outlined' multiline
                                   value={!cocktail.instructions ? "" : cocktail.instructions}
                                   onChange={(e) => changeCocktailValue("instructions", e.target.value)}
                        />
                    </Box>
                </Stack>
            </Paper>
            <Box display={'flex'} justifyContent={'flex-end'}>
                <Button variant='contained' onClick={() => saveHandler()}>Сохранить</Button>
            </Box>
        </Box>
    )
}