import { useState } from "react";
import { useLocation } from "react-router-dom";
import { Box, Tabs, Typography, useMediaQuery, useTheme } from "@mui/material";
import SectionWrapper from "@components/SectionWrapper";
import ComplexNavText from "@root/components/ComplexNavText";
import { useTariffs } from "@root/utils/hooks/useTariffs";
import { updateTariffs, useTariffStore } from "@root/stores/tariffs";
import { enqueueSnackbar } from "notistack";
import { CustomTab } from "@root/components/CustomTab";
import TariffCard from "./TariffCard";
import NumberIcon from "@root/components/NumberIcon";
import { currencyFormatter } from "@root/utils/currencyFormatter";
import { calcTariffPrices } from "@root/utils/calcTariffPrices";
import { getMessageFromFetchError } from "@frontend/kitui";
import FreeTariffCard from "./FreeTariffCard";
import { addTariffToCart } from "@root/stores/user";
import { useDiscountStore } from "@root/stores/discounts";
import { useCustomTariffsStore } from "@root/stores/customTariffs";


export default function TariffPage() {
    const theme = useTheme();
    const upMd = useMediaQuery(theme.breakpoints.up("md"));
    const location = useLocation();
    const tariffs = useTariffStore(state => state.tariffs);
    const [tabIndex, setTabIndex] = useState<number>(0);
    const discounts = useDiscountStore(state => state.discounts);
    const customTariffs = useCustomTariffsStore(state => state.customTariffs);

    const unit: string = String(location.pathname).slice(9);

    const StepperText: Record<string, string> = { volume: "Тарифы на объём", time: "Тарифы на время" };

    useTariffs({
        apiPage: 0,
        tariffsPerPage: 100,
        onNewTariffs: updateTariffs,
        onError: error => {
            const errorMessage = getMessageFromFetchError(error);
            if (errorMessage) enqueueSnackbar(errorMessage);
        }
    });

    function handleTariffItemClick(tariffId: string) {
        addTariffToCart(tariffId).then(() => {
            enqueueSnackbar("Тариф добавлен в корзину");
        }).catch(error => {
            const message = getMessageFromFetchError(error);
            if (message) enqueueSnackbar(message);
        });
    }

    const filteredTariffs = tariffs.filter(tariff => {
        return tariff.privilegies.map(p => p.type).includes("day") === (unit === "time") && !tariff.isDeleted;
    });

    const tariffElements = filteredTariffs.map((tariff, index) => {
        const { price, priceWithDiscounts } = calcTariffPrices(tariff,discounts,customTariffs);

        return (
            <TariffCard
                key={tariff._id}
                icon={<NumberIcon
                    number={index + 1}
                    color={unit === "time" ? "#7E2AEA" : "#FB5607"}
                    backgroundColor={unit === "time" ? "#EEE4FC" : "#FEDFD0"}
                />}
                buttonText="Выбрать"
                headerText={tariff.name}
                text={tariff.privilegies.map(p => `${p.name} - ${p.amount}`)}
                onButtonClick={() => handleTariffItemClick(tariff._id)}
                price={<>
                    {price !== undefined && price !== priceWithDiscounts &&
                        <Typography variant="oldPrice">{currencyFormatter.format(price / 100)}</Typography>
                    }
                    {priceWithDiscounts !== undefined &&
                        <Typography variant="price">{currencyFormatter.format(priceWithDiscounts / 100)}</Typography>
                    }
                </>}
            />
        );
    });

    if (tariffElements.length < 6) tariffElements.push(<FreeTariffCard key="free_tariff_card" />);
    else tariffElements.splice(5, 0, <FreeTariffCard key="free_tariff_card" />);

    return (
        <SectionWrapper
            maxWidth="lg"
            sx={{
                mt: "20px",
                mb: upMd ? "90px" : "63px",
                display: "flex",
                flexDirection: "column",
            }}
        >
            {upMd && <ComplexNavText text1="Все тарифы — " text2={StepperText[unit]} />}
            <Typography variant="h4" sx={{ marginBottom: "23px", mt: "20px" }}>
                {StepperText[unit]}
            </Typography>
            <Tabs
                TabIndicatorProps={{ sx: { display: "none" } }}
                value={tabIndex}
                onChange={(event, newValue) => setTabIndex(newValue)}
                variant="scrollable"
                scrollButtons={false}
            >
                <CustomTab value={0} label="Шаблонизатор" />
                <CustomTab value={1} label="Опросник" />
                <CustomTab value={2} label="Сокращатель ссылок" />
            </Tabs>
            <Box sx={{
                mt: "40px",
                mb: "30px",
                display: "grid",
                gap: "40px",
                gridTemplateColumns: "repeat(auto-fit, minmax(300px, 360px))",
            }}>
                {tariffElements}
            </Box>
        </SectionWrapper>
    );
}
