import { FC, useEffect, useRef, useState } from "react";
import { isNull } from "lodash";
import type { Swiper as SwiperClass } from "swiper/types";
import { DealSchema } from "@/lib/client";
import ProductsTabSlider from "@/modules/dealModularEditorTabs/FulfillmentBase/mobile/components/ProductsTabSlider/ProductsTabSlider";
import ProductsTabTable from "@/modules/dealModularEditorTabs/FulfillmentBase/mobile/components/ProductsTabTable/ProductsTabTable";
import ProductsTabViewAffix, {
    ProductsTabView,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/mobile/components/ProductsTabViewAffix/ProductsTabViewAffix";
import { FulfillmentBaseContextProvider } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";

type Props = {
    value: DealSchema;
};

const ProductsTab: FC<Props> = ({ value }) => {
    const [view, setView] = useState<ProductsTabView>(ProductsTabView.SLIDER);
    const swiperRef = useRef<SwiperClass | null>(null);
    const targetSlideIndex = useRef<number>(null);

    const onProductRowSelect = async (productIndex: number) => {
        targetSlideIndex.current = productIndex;
        setView(ProductsTabView.SLIDER);
    };

    useEffect(() => {
        if (
            view === ProductsTabView.SLIDER &&
            !isNull(targetSlideIndex.current)
        ) {
            swiperRef.current?.slideTo(targetSlideIndex.current);
            targetSlideIndex.current = null;
        }
    }, [view]);

    return (
        <FulfillmentBaseContextProvider deal={value}>
            {view === ProductsTabView.SLIDER ? (
                <ProductsTabSlider swiperRef={swiperRef} />
            ) : (
                <ProductsTabTable onSelect={onProductRowSelect} />
            )}
            <ProductsTabViewAffix
                value={view}
                onChange={value => setView(value as ProductsTabView)}
            />
        </FulfillmentBaseContextProvider>
    );
};

export default ProductsTab;
