import { setPageTitle } from '@/store/themeConfigSlice';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Link from 'next/link';

import { coloredToast } from '@/lib/toast';
import { useRouter } from 'next/router';
import BundlingForm from '@/components/Promotions/FormBundling';
import { SaveBundling } from '@/utils/saveBundle';
import { getProductsList } from '@/lib/product';
import CloudinaryScript from '@/components/CloudinaryScript';

const AddBundling = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Promotion Add'));
        setIsMounted(true);
    }, []);
    const [isMounted, setIsMounted] = useState(false);

    const router = useRouter();

    const [bundling, setBundling] = useState<any>({
        promotion_name: '',
        promotion_start: '',
        promotion_end: '',
        promotion_is_active: false,
        promotion_case: [],
    });
    const [isLoading, setIsLoading] = useState(false);
    const [allProduct, setAllProduct] = useState<any>([]);
    const [productMaster, setProductMaster] = useState<any>([]);
    const [productSlave, setProductSlave] = useState<any>([]);
    const [productBundling, setProductBundling] = useState<any>([]);

    const fetchMasterProduct = async () => {
        const resProductCat = await getProductsList();
        setAllProduct(resProductCat);
    };
    useEffect(() => {
        fetchMasterProduct();
    }, []);

    const savePromotion = async () => {
        // setIsLoading(true);

        const bundlingForm = {
            promotion_name: bundling.promotion_name,
            promotion_start: bundling.promotion_start,
            promotion_end: bundling.promotion_end,
            promotion_is_active: bundling.promotion_is_active,
            promotion_case: bundling.promotion_case,
        };

        const validationSave = SaveBundling(bundlingForm);

        if (validationSave.status === false) {
            setIsLoading(false);
            return;
        }

        try {
            const api_url = process.env.API_URL;
            const payload = {
                data: validationSave.data,
            };
            // login credential
            const response = await fetch(`${api_url}api/bundle/store`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });

            // condition add order failed
            if (!response.ok) {
                const res = await response.json();
                coloredToast('warning', res.message);
                setIsLoading(false);
                return;
            }

            coloredToast('success', `promotion created successfully`);
            // router.push('/promotions');
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'something went wrong');
        }

        setIsLoading(false);
    };

    return (
        <>
            <CloudinaryScript />
            {isMounted && (
                <>
                    <div className="mb-3">
                        <ul className="flex space-x-2 rtl:space-x-reverse">
                            <li>
                                <Link href="/promotions" className="text-primary hover:underline">
                                    Promotion
                                </Link>
                            </li>
                            <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                                <span>new</span>
                            </li>
                        </ul>
                    </div>
                    <div className="flex flex-col gap-2.5 xl:flex-row">
                        <BundlingForm bundling={bundling} setBundling={setBundling} setProductBundling={setProductBundling} productBundling={productBundling} allProduct={allProduct} />
                    </div>

                    <div className="mt-6 w-full  xl:w-80">
                        <div className="panel">
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                                <button type="button" disabled={isLoading} onClick={savePromotion} className="btn btn-success w-full gap-2">
                                    {isLoading ? (
                                        <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                    ) : (
                                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 shrink-0 ltr:mr-2 rtl:ml-2">
                                            <path
                                                d="M3.46447 20.5355C4.92893 22 7.28595 22 12 22C16.714 22 19.0711 22 20.5355 20.5355C22 19.0711 22 16.714 22 12C22 11.6585 22 11.4878 21.9848 11.3142C21.9142 10.5049 21.586 9.71257 21.0637 9.09034C20.9516 8.95687 20.828 8.83317 20.5806 8.58578L15.4142 3.41944C15.1668 3.17206 15.0431 3.04835 14.9097 2.93631C14.2874 2.414 13.4951 2.08581 12.6858 2.01515C12.5122 2 12.3415 2 12 2C7.28595 2 4.92893 2 3.46447 3.46447C2 4.92893 2 7.28595 2 12C2 16.714 2 19.0711 3.46447 20.5355Z"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                            <path
                                                d="M17 22V21C17 19.1144 17 18.1716 16.4142 17.5858C15.8284 17 14.8856 17 13 17H11C9.11438 17 8.17157 17 7.58579 17.5858C7 18.1716 7 19.1144 7 21V22"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                            />
                                            <path opacity="0.5" d="M7 8H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                        </svg>
                                    )}
                                    Save
                                </button>
                            </div>
                        </div>
                    </div>
                </>
            )}
        </>
    );
};
export default AddBundling;
