import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/flatpickr.css';
import Select from 'react-select';
import { Fragment, useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { coloredToast } from '@/lib/toast';

const ML_WAIT_TIMEOUT_MS = 8000;
const ML_POLL_INTERVAL_MS = 100;

interface Slave {
    id: number;
    label: string;
    price_bundle: number;
    qty_bundle: number | null;
    reg_price_bundle: number | null;
    sku_bundle: string;
    value: string;
    sale_price_bundle: number | null;
    image_bundle: string;
}
interface BundlingCase {
    id: number;
    master: string[];
    product_item: Slave[];
    bundling_type: string;
}

interface Bundling {
    promotion_name: string;
    promotion_start: Date;
    promotion_end: Date;
    promotion_is_active: boolean;
    promotion_case: BundlingCase[];
}

interface BundlingProps {
    bundling: Bundling;
    setBundling: React.Dispatch<React.SetStateAction<Bundling>>;
    setProductBundling: React.Dispatch<React.SetStateAction<any>>;
    productBundling: [];
    allProduct: [];
}

interface CustomWindow extends Window {
    cloudinary: any;
}

declare let window: CustomWindow;

const BundlingForm: React.FC<BundlingProps> = ({ bundling, setBundling, setProductBundling, productBundling, allProduct }) => {
    const handleChange = (e: any) => {
        setBundling((prev) => ({
            ...prev,
            [e.target.name]: e.target.value,
        }));
    };

    const changeIsActive = (e: any) => {
        setBundling((prev) => ({
            ...prev,
            promotion_is_active: e.target.checked,
        }));
    };

    const [productMaster, setProductMaster] = useState<any>([]);

    const [productSlave, setProductSlave] = useState<any>([]);

    const sortedProduct = () => {
        const formatMaster = (option: any, includeImage: boolean = true) => {
            const { _id, product_title } = option;
            return {
                value: _id,
                label: product_title,
            };
        };
        const formatSlave = (option: any, includeImage: boolean = true) => {
            const { _id, product_title, product_sku, product_reg_price, product_sale_price, product_price, product_images } = option;
            const id = _id;
            const sku = product_sku;
            const price = product_price;
            const reg_price = product_reg_price;
            const sale_price = product_sale_price;
            const image = includeImage ? product_images[0] : '';
            return {
                id: id,
                value: product_title.charAt(0).toUpperCase() + product_title.slice(1),
                label: product_title.charAt(0).toUpperCase() + product_title.slice(1),
                sku_bundle: sku,
                price_bundle: price,
                reg_price_bundle: reg_price,
                sale_price_bundle: sale_price,
                image_bundle: image,
                ...(includeImage ? {} : { qty_bundle: 0 }),
            };
        };

        const formattedMasterProduct = allProduct.map((option: any) => formatMaster(option, false));
        const formattedSlaveProduct = allProduct.map((option: any) => formatSlave(option, false));

        setProductMaster(formattedMasterProduct);
        setProductSlave(formattedSlaveProduct);
    };

    useEffect(() => {
        sortedProduct();
    }, [allProduct]);

    const addItem = () => {
        setBundling((prev: any) => {
            const maxId = prev.promotion_case.reduce((max: number, item: any) => {
                return item.id > max ? item.id : max;
            }, 0);

            return {
                ...prev,
                promotion_case: [
                    ...prev.promotion_case,
                    {
                        id: maxId + 1,
                        master: '',
                        product_item: [],
                        bundling_type: 'label',
                    },
                ],
            };
        });
    };

    const removeItem = (itemToRemove: BundlingCase) => {
        if (itemToRemove) {
            setBundling((prev) => ({
                ...prev,
                promotion_case: prev.promotion_case.filter((item) => item.id !== itemToRemove.id),
            }));
        }
    };

    const handleChangeMaster = (selectedOptions: any, id: number) => {
        console.log(selectedOptions, id);

        if (!selectedOptions) return;

        setBundling((prev) => ({
            ...prev,
            promotion_case: prev.promotion_case.map((item) => {
                if (item.id === id) {
                    return {
                        ...item,
                        master: selectedOptions,
                    };
                }
                return item;
            }),
        }));

        const selectedProduct = allProduct.find((product: any) => product.product_title === selectedOptions.value);

        if (selectedProduct) {
            setProductBundling(selectedProduct);
        }
    };
    // const handleChangeSlave = (selectedOptions: any[], id: number) => {
    //     setBundling((prev: any) => {
    //         return {
    //             ...prev,
    //             promotion_case: prev.promotion_case.map((item: any) => {
    //                 if (item.id === id) {
    //                     return {
    //                         ...item,
    //                         slave: selectedOptions,
    //                     };
    //                 }
    //                 return item;
    //             }),
    //         };
    //     });
    //     if (selectedOptions.length > 0) {
    //         setProductBundling((prev: any) => {
    //             const maxId = prev.product_items.reduce((max: number, item: any) => (item.id > max ? item.id : max), 0);

    //             const optionsWithId = selectedOptions.map((option: any) => ({
    //                 ...option,
    //                 id: maxId + 1,
    //             }));

    //             if (selectedOptions.length > 1) {
    //                 return {
    //                     ...prev,
    //                     product_items: [
    //                         ...prev.product_items.filter((item: any) => !selectedOptions.some((option: any) => option.value === item.value)),
    //                         ...optionsWithId.map((option, index) => ({
    //                             ...option,
    //                             id: prev.product_items.length + index,
    //                         })),
    //                     ],
    //                 };
    //             } else {
    //                 return {
    //                     ...prev,
    //                     product_items: [...prev.product_items, ...optionsWithId],
    //                 };
    //             }
    //         });
    //     }
    // };

    const handleChangeSlave = (selectedOptions: any[], id: number) => {
        // Update the bundling state
        setBundling((prev: any) => {
            return {
                ...prev,
                promotion_case: prev.promotion_case.map((item: any) => {
                    if (item.id === id) {
                        return {
                            ...item,
                            product_item: selectedOptions,
                        };
                    }
                    return item;
                }),
            };
        });

        setProductBundling((prev: any) => {
            const tempSelected = selectedOptions.map((option, index) => ({
                ...option,
                id: prev.product_bundle_items?.length > 0 ? prev.product_bundle_items.length + index : 1,
                image_bundle: option.image_bundle || '', // Menambahkan properti image_bundle dengan nilai default kosong
            }));

            return {
                ...prev,
                product_bundle_items: tempSelected,
            };
        });
    };

    return (
        <div className="panel flex-1 px-0 py-6 ltr:xl:mr-6 rtl:xl:ml-6">
            <div className="flex flex-wrap justify-between px-4">
                <div className="mb-4 w-full lg:w-1/2 lg:max-w-fit">
                    <div className="text-lg">Bundling Promotion : </div>

                    <div className="mt-4 flex items-center">
                        <label htmlFor="promotionTitle" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                            Title
                        </label>
                        <input type="text" id="promotionTitle" name="promotion_name" value={bundling.promotion_name} onChange={handleChange} className="form-input w-2/3 lg:w-[250px]" />
                    </div>

                    <div className="mt-4 flex items-center">
                        <label htmlFor="promotionStart" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                            Start Date
                        </label>
                        <Flatpickr
                            options={{
                                dateFormat: 'Y-m-d',
                                position: 'auto left',
                                time_24hr: true,
                            }}
                            value={bundling.promotion_start}
                            className="form-input w-2/3 lg:w-[250px]"
                            placeholder="yyyy-mm-dd"
                            onChange={(startDate) =>
                                setBundling((prev) => ({
                                    ...prev,
                                    promotion_start: new Date(startDate[0]),
                                }))
                            }
                        />
                    </div>
                    <div className="mt-4 flex items-center">
                        <label htmlFor="promotionEnd" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                            End Date
                        </label>
                        <Flatpickr
                            options={{
                                dateFormat: 'Y-m-d',
                                position: 'auto left',
                                time_24hr: true,
                            }}
                            value={bundling.promotion_end}
                            className="form-input w-2/3 lg:w-[250px]"
                            placeholder="yyyy-mm-dd"
                            onChange={(endDate) =>
                                setBundling((prev) => ({
                                    ...prev,
                                    promotion_end: new Date(endDate[0]),
                                }))
                            }
                        />
                    </div>

                    <div className="mt-4 flex items-center">
                        <label htmlFor="promotionIsActive" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                            Is Active ?
                        </label>
                        <label className="relative h-6 w-12">
                            <input
                                type="checkbox"
                                onChange={changeIsActive}
                                checked={bundling.promotion_is_active}
                                className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                id="promotion_is_active"
                            />
                            <span className="outline_checkbox bg-icon block h-full rounded-full border-2 border-[#ebedf2] before:absolute before:bottom-1 before:left-1 before:h-4 before:w-4 before:rounded-full before:bg-[#ebedf2] before:bg-[url(/assets/images/close.svg)] before:bg-center before:bg-no-repeat before:transition-all before:duration-300 peer-checked:border-primary peer-checked:before:left-7 peer-checked:before:bg-primary peer-checked:before:bg-[url(/assets/images/checked.svg)] dark:border-white-dark dark:before:bg-white-dark"></span>
                        </label>
                    </div>
                </div>
                <div className="mb-4 w-full lg:w-1/2">
                    <div className="text-lg">Bundling Cases : </div>
                    <div className="mb-8 mt-2 table w-full">
                        <table>
                            <thead>
                                <tr>
                                    <th className="w-1">Master</th>
                                    <th className="w-1">Slave</th>
                                    <th className="w-1">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {bundling.promotion_case.length <= 0 && (
                                    <tr>
                                        <td colSpan={3} className="!text-center font-semibold">
                                            No Case Available
                                        </td>
                                    </tr>
                                )}
                                {bundling.promotion_case.map((item) => (
                                    <tr className="w-full align-top" key={item.id}>
                                        <td className="w-1/3">
                                            <Select options={productMaster} value={item.master} onChange={(options: any) => handleChangeMaster(options, item.id)} />
                                        </td>
                                        <td className="w-2/3">
                                            {item.master && (
                                                <Select
                                                    options={productSlave}
                                                    value={item.product_item}
                                                    onChange={(options: any) => handleChangeSlave(Array.isArray(options) ? options : [options], item.id)}
                                                    isMulti
                                                />
                                            )}
                                        </td>
                                        <td>
                                            <button type="button" onClick={() => removeItem(item)}>
                                                <svg
                                                    xmlns="http://www.w3.org/2000/svg"
                                                    width="20"
                                                    height="20"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                >
                                                    <line x1="18" y1="6" x2="6" y2="18"></line>
                                                    <line x1="6" y1="6" x2="18" y2="18"></line>
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>

                        <div className="mb-4 ml-3 flex items-center sm:flex-wrap">{/* <ItemVariant selectedOption={selectedOption} items={items} setItems={setItems} product={product} /> */}</div>
                    </div>
                    <div className="m-4 flex flex-row gap-2">
                        <button type="button" className="btn btn-outline-primary btn-sm" onClick={addItem}>
                            Add Case
                        </button>
                    </div>
                </div>
            </div>
            <FormProductBundling productBundling={bundling} setProductBundling={setBundling} productItems={productBundling} setProductItems={setProductBundling} />
        </div>
    );
};

export default BundlingForm;

const FormProductBundling = ({ productBundling, setProductBundling, productItems, setProductItems }: { productBundling: any; setProductBundling: any; productItems: any; setProductItems: any }) => {
    const [images, setImages] = useState<any>([]);
    const [isUploading, setIsUploading] = useState(false);
    const [itemUploadId, setItemUploadId] = useState(0);
    const itemUploadIdRef = useRef(itemUploadId);
    const masterIdRef = useRef<number | null>(null);
    const mlRef = useRef<any>(null);
    const waitTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
    const handlersRef = useRef({
        show: () => {},
        hide: () => {},
        insert: (_res: any) => {},
    });

    const [ml, setMl] = useState<any>(null);

    const config = {
        cloud_name: 'aurumlab',
        api_key: '637983323526145',
        folder: { path: 'aurumlab/product/images' },
    };

    const clearWaitTimer = () => {
        if (waitTimerRef.current) {
            clearInterval(waitTimerRef.current);
            waitTimerRef.current = null;
        }
    };

    const resetUploadState = () => {
        setIsUploading(false);
        itemUploadIdRef.current = 0;
        masterIdRef.current = null;
        setItemUploadId(0);
    };

    const ensureMediaLibrary = () => {
        if (mlRef.current) return mlRef.current;
        if (typeof window.cloudinary === 'undefined') return null;

        const mlInstance = window.cloudinary.createMediaLibrary(config, {
            insertHandler: (res: any) => handlersRef.current.insert(res),
            showHandler: () => handlersRef.current.show(),
            hideHandler: () => handlersRef.current.hide(),
        });

        mlRef.current = mlInstance;
        setMl(mlInstance);
        return mlInstance;
    };

    const openMediaLibrary = () => {
        const instance = ensureMediaLibrary();
        if (!instance) return false;
        clearWaitTimer();
        instance.show();
        return true;
    };

    const handleUploadClick = (id: number, masterId: number) => {
        setItemUploadId(id);
        itemUploadIdRef.current = id;
        masterIdRef.current = masterId;
        setIsUploading(true);

        if (openMediaLibrary()) return;

        clearWaitTimer();
        const startedAt = Date.now();
        waitTimerRef.current = setInterval(() => {
            if (openMediaLibrary()) return;
            if (Date.now() - startedAt >= ML_WAIT_TIMEOUT_MS) {
                clearWaitTimer();
                resetUploadState();
                coloredToast('danger', 'Cloudinary Media Library gagal dimuat. Coba refresh halaman.');
            }
        }, ML_POLL_INTERVAL_MS);
    };

    useEffect(() => {
        ensureMediaLibrary();
        return () => clearWaitTimer();
    }, []);

    useEffect(() => {
        if (ml && masterIdRef.current !== null && isUploading) {
            ml.show();
        }
    }, [ml]);

    handlersRef.current.show = () => {
        setIsUploading(true);
    };

    handlersRef.current.insert = (res: any) => {
        const masterId = masterIdRef.current;
        const id = itemUploadIdRef.current;

        if (!masterId) {
            console.error('Master ID is null');
            return;
        }

        const imageUrl = res.assets[0].url.toString();

        if (imageUrl) {
            setProductBundling((prev: any) => ({
                ...prev,
                promotion_case: prev.promotion_case.map((item: any) => {
                    if (item.id === masterId) {
                        return {
                            ...item,
                            product_item: item.product_item.map((slaveItem: any, index: number) => {
                                if (index === id) {
                                    return {
                                        ...slaveItem,
                                        image_bundle: imageUrl,
                                    };
                                }
                                return slaveItem;
                            }),
                        };
                    }
                    return item;
                }),
            }));

            clearWaitTimer();
            setIsUploading(false);
        }
    };

    handlersRef.current.hide = () => {
        clearWaitTimer();
        resetUploadState();
    };

    //   const addImage = (newImage: any) => {
    //       setImages((prevImages: any) => [...prevImages, newImage]);
    // };

    //   useEffect(() => {
    //       if (images.length > 0) {
    //           setProductItems((prev: any) => ({
    //               ...prev,
    //               product_bundle_items: prev.product_bundle_items.map((item: any) => ({
    //                   ...item,
    //                   image_bundle: images,
    //               })),
    //           }));
    //       }
    //   }, [images]);

    const handleChangeSlave = (e: React.ChangeEvent<HTMLInputElement>, id: number, masterId: number, field: string) => {
        setProductBundling((prev: any) => ({
            ...prev,
            promotion_case: prev.promotion_case.map((item: any) => {
                if (item.id === masterId) {
                    return {
                        ...item,
                        product_item: item.product_item.map((slaveItem: any, index: number) => {
                            if (index === id) {
                                return {
                                    ...slaveItem,
                                    [field]: Number(e.target.value),
                                };
                            }
                            return slaveItem;
                        }),
                    };
                }
                return item;
            }),
        }));

        setProductItems((prev: any) => ({
            ...prev,
            product_bundle_items: prev.product_bundle_items.map((item: any) => {
                if (item.id === masterId) {
                    return {
                        ...item,
                        [field]: Number(e.target.value),
                    };
                }
                return item;
            }),
        }));
    };

    // const handleSlaveImageChange = (e: React.ChangeEvent<HTMLInputElement>, bundleItem: number, field: string) => {
    //     const file = e.target.files?.[0];
    //     if (!file) return;

    //     setProductItems((prev: any) => ({
    //         ...prev,
    //         product_bundle_items: prev.product_bundle_items.map((item: any, index: number) => {
    //             if (index === bundleItem) {
    //                 return {
    //                     ...item,
    //                     [field]: URL.createObjectURL(file),
    //                 };
    //             }
    //             return item;
    //         }),
    //     }));
    // };

    return (
        <>
            {productBundling.promotion_case.length > 0 &&
                productBundling.promotion_case.map((item: any, index: number) => (
                    <div key={`bundling` + item.id + index}>
                        <div className="mx-auto mt-6 pl-6 text-xl font-bold">
                            <h1>{item.master.label}</h1>
                        </div>
                        <div className="flex flex-wrap gap-4">
                            {item.product_item.map((slave: any, index: number) => (
                                <div key={`slave-data-` + index}>
                                    <div className="panel">
                                        <div className="panel-body">
                                            <div className="mt-4 flex items-center gap-8">
                                                <label htmlFor="promotionTitle" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2 ">
                                                    Bundling Name
                                                </label>
                                                <input type="text" id="promotionTitle" name="promotion_name" value={slave.label} className="form-input lg:w-[250px]" readOnly />
                                            </div>
                                            <div className="mt-4 flex items-center">
                                                <label htmlFor="bundling_regular_price" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                                    Bundling Regular Price
                                                </label>
                                                <input
                                                    type="number"
                                                    id="bundling_regular_price"
                                                    name="bundling_regular_price"
                                                    onChange={(e) => handleChangeSlave(e, index, item.id, 'reg_price_bundle')}
                                                    className="form-input lg:w-[250px]"
                                                    min={0}
                                                />
                                            </div>
                                            <div className="mt-4 flex items-center">
                                                <label htmlFor="bundling_sale_price" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                                    Bundling Sale Price
                                                </label>
                                                <input
                                                    type="number"
                                                    min={0}
                                                    id="bundling_sale_price"
                                                    name="bundling_sale_price"
                                                    onChange={(e) => handleChangeSlave(e, index, item.id, 'sale_price_bundle')}
                                                    className="form-input lg:w-[250px]"
                                                />
                                            </div>
                                            <div className="mt-4 flex items-center">
                                                <label htmlFor="bundling_qty" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                                    Quantity
                                                </label>
                                                <input
                                                    type="number"
                                                    min={0}
                                                    id="bundling_qty"
                                                    name="bundling_qty"
                                                    onChange={(e) => handleChangeSlave(e, index, item.id, 'qty_bundle')}
                                                    className="form-input lg:w-[250px]"
                                                />
                                            </div>
                                            <div className="mt-4 flex items-center">
                                                <div className="mt-2">
                                                    {slave.image_bundle ? (
                                                        <>
                                                            <img src={slave.image_bundle} alt="Bundling Image" height={120} width={120} />

                                                            <button onClick={() => handleUploadClick(index, item.id)} className="mt-5" id={item.id}>
                                                                Change Image
                                                            </button>
                                                        </>
                                                    ) : (
                                                        <button onClick={() => handleUploadClick(index, item.id)} className="mt-5" id={item.id}>
                                                            <svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24" fill="none">
                                                                <path
                                                                    d="M2 12.5001L3.75159 10.9675C4.66286 10.1702 6.03628 10.2159 6.89249 11.0721L11.1822 15.3618C11.8694 16.0491 12.9512 16.1428 13.7464 15.5839L14.0446 15.3744C15.1888 14.5702 16.7369 14.6634 17.7765 15.599L21 18.5001"
                                                                    stroke="currentColor"
                                                                    strokeWidth="1.5"
                                                                    strokeLinecap="round"
                                                                />
                                                                <path d="M15 5.5H18.5M18.5 5.5H22M18.5 5.5V9M18.5 5.5V2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                                <path
                                                                    d="M22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 10.8717 2 9.87835 2.02008 9M12 2C7.28595 2 4.92893 2 3.46447 3.46447C3.03965 3.88929 2.73806 4.38921 2.52396 5"
                                                                    stroke="currentColor"
                                                                    strokeWidth="1.5"
                                                                    strokeLinecap="round"
                                                                />
                                                            </svg>
                                                        </button>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                ))}
        </>
    );
};
