import { useMemo, useState } from 'react';
import styled from 'styled-components';
import { setOption } from '../../api/promoApi';
import { useDebounceBatch } from '../../hooks/useDebounceBatch';
import {reachGoal} from "../../hooks/useYM";


interface CategoriesSectionProps {
    categories: string[];
    selectedCategories: string[];
    onLocalChange: (categories: string[]) => void;
    onSaved: () => void;
}

export function CategoriesSection({
                                      categories,
                                      selectedCategories,
                                      onLocalChange,
                                      onSaved,
                                  }: CategoriesSectionProps) {
    const [expanded, setExpanded] = useState(true);
    const [loadingCategories, setLoadingCategories] = useState<string[]>([]);

    const maxVisibleCategories = 7;

    const dataToShow = useMemo(() => {
        if (expanded) return categories;

        return (selectedCategories.length > 0 ? selectedCategories : categories)
            .slice(0, maxVisibleCategories);
    }, [categories, expanded, selectedCategories]);

    const sendUpdatedCategories = useDebounceBatch<string>(async categoryNames => {
        let nextCategories = [...selectedCategories];

        reachGoal('ac_set_categories');
        categoryNames.forEach(categoryName => {
            if (nextCategories.includes(categoryName)) {
                nextCategories = nextCategories.filter(item => item !== categoryName);
            } else {
                nextCategories.push(categoryName);
            }
        });

        onLocalChange(nextCategories);
        await setOption('categories', nextCategories);
        onSaved();
    }, 1500);

    function toggleCategory(category: string) {
        if (loadingCategories.includes(category)) return;

        setLoadingCategories(current => [...current, category]);

        sendUpdatedCategories(category).finally(() => {
            setLoadingCategories(current => current.filter(item => item !== category));
        });
    }

    if (categories.length === 0) {
        return null;
    }

    return (
        <Block>
            <Header>
                <h3>Что добавить в корзину?</h3>
                <p>Выберите группы продуктов, которые должны обязательно попасть в корзину</p>
            </Header>

            <Wrapper>
                <Grid>
                    {dataToShow.map(category => (
                        <CategoryButton
                            key={category}
                            type="button"
                            $active={selectedCategories.includes(category)}
                            $loading={loadingCategories.includes(category)}
                            onClick={() => toggleCategory(category)}
                        >
                            <span>{category}</span>
                        </CategoryButton>
                    ))}

                    {dataToShow.length > 0 && (
                        <ToggleButton
                            type="button"
                            $collapsed={!expanded}
                            onClick={() => setExpanded(value => !value)}
                        >
                            {!expanded && dataToShow.length < selectedCategories.length
                                ? `+${selectedCategories.length - dataToShow.length}`
                                : ''}
                            <svg viewBox="0 0 24 24" fill="none">
                                <polyline points="18 15 12 9 6 15" />
                            </svg>
                        </ToggleButton>
                    )}
                </Grid>
            </Wrapper>
        </Block>
    );
}

const Block = styled.div``;

const Header = styled.div`
    h3 {
        font-size: 16px;
        line-height: 19px;
        color: ${({ theme }) => theme.colors.darkGreen};
        margin-bottom: 4px;
        font-weight: 350;
    }

    p {
        font-size: 14px;
        color: ${({ theme }) => theme.colors.gray};
        margin-bottom: 16px;
        font-weight: 350;
    }
`;

const Wrapper = styled.div`
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
`;

const Grid = styled.div`
    gap: 10px;
    display: flex;
    flex-wrap: wrap;
`;

const CategoryButton = styled.button<{ $active: boolean; $loading: boolean }>`
    position: relative;
    overflow: hidden;
    height: 32px;
    padding: 8px 16px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 1.2s;
    background-color: ${({ $active }) => ($active ? '#0C3B2E' : '#F1FAF0')};
    span {
        color: ${({ $active }) => ($active ? '#F1FAF0' : '#0C3B2E')};
    }

    &:hover {
        background-color: ${({ $active }) => ($active ? '#0C3B2E' : '#e4f0de')};
    }

    ${({ $loading }) => $loading && `
        color: #0C3B2E;

        &:before,
        &:after {
            content: '';
            display: flex;
            width: 100%;
            height: 100%;
            justify-content: center;
            align-items: center;
            position: absolute;
            inset: 0;
        }

        &:before {
            background: linear-gradient(79deg, #FFBA00 0%, #FFEC47 31%, #C4E30F 63%, #5EA12D 98%) 100%;
            animation: opacityAnim 1s ease-in-out 0s infinite alternate;
        }

        &:after {
            background: linear-gradient(79deg, #5EA12D 2%, #C4E30F 38%, #FFEC47 69%, #FFBA00 100%) 100%;
            animation: opacityAnim 1s ease-in-out -1s infinite alternate;
        }

        span {
            position: relative;
            z-index: 2;
        }
    `}
`;

const ToggleButton = styled.button<{ $collapsed: boolean }>`
    height: 32px;
    min-width: 32px;
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: center;
    background-color: #f2f9ef;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: 0.2s;
    padding: 6px 8px 6px 16px;
    color: ${({ theme }) => theme.colors.darkGreen};
    font-size: 14px;
    font-weight: 350;

    &:hover {
        background-color: #e4f0de;
    }

    svg {
        width: 18px;
        height: 18px;
        stroke: ${({ theme }) => theme.colors.darkGreen};
        stroke-width: 2;
        stroke-linecap: round;
        stroke-linejoin: round;
        transition: transform 0.3s ease;
        transform: ${({ $collapsed }) => ($collapsed ? 'rotate(180deg)' : 'none')};
    }
`;