import { setPageTitle } from '@/store/themeConfigSlice';
import { Fragment, useEffect, useState, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import Link from 'next/link';
import Swal from 'sweetalert2';
import { coloredToast } from '@/lib/toast';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import NumberFormatter from '@/lib/ribuan';
import { logActivity } from '@/utils/activityLogger';

type Variation = {
    variation_sku: string;
    variation_reg_price: number;
    variation_sale_price: number;
};
interface Product {
    id: string;
    product_sku: string;
    product_title: string;
    variation_price_change: string;
    product_reg_price: number;
    product_sale_price: number;
    variations?: Variation[];
}

const BulkPricing = () => {
    const [isMounted, setIsMounted] = useState(false);
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(setPageTitle('Bulk Pricing'));
        setIsMounted(true);
    }, []);

    const headerProducts = [
        'product_sku',
        'product_title',
        'product_reg_price',
        'product_sale_price',
        'product_variation',
        'ring_size',
        'color',
        'variation_reg_price',
        'variation_sale_price',
    ];

    const getAttributeValue = (variant: any, attrName: string): string => {
        const attributes = Array.isArray(variant?.attributes) ? variant.attributes : [];
        const attr = attributes.find(
            (item: any) => String(item?.name || '').toLowerCase() === attrName.toLowerCase()
        );

        if (!attr || attr.value == null || attr.value === '') return '';

        if (typeof attr.value === 'object') {
            const label = attr.value.label ?? attr.value.value;
            return label != null && label !== '' ? String(label) : '';
        }

        return String(attr.value);
    };

    const getRingSize = (variant: any): string => {
        if (variant?.ring_size != null && variant.ring_size !== '') {
            return String(variant.ring_size);
        }

        const fromAttr = getAttributeValue(variant, 'ring size');
        if (fromAttr) return fromAttr;

        // Fallback: parse dari sku_variation (contoh: LAUCC6K221-r12 / LAUCC6K221-16)
        const sku = String(variant?.sku_variation || '');
        const match = sku.match(/-r?(\d+)$/i);
        return match?.[1] ?? '';
    };

    const getColor = (variant: any): string => {
        if (variant?.color != null && variant.color !== '') {
            return String(variant.color);
        }
        return getAttributeValue(variant, 'color');
    };

    const [products, setProducts] = useState([]);

    useEffect(() => {
        const api_url = process.env.API_URL;

        fetch(`${api_url}api/products/product-list-price`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // Include this option
        })
            .then((res) => res.json())
            .then((json) => {
                const formattedProduct = json.map((product: any) => ({
                    product_sku: product.product_sku,
                    product_title: product.product_title,
                    product_reg_price: product.product_reg_price,
                    product_sale_price: product.product_sale_price,
                    product_variation: (product.product_items ?? []).map((variant: any) => ({
                        reg_price: variant.reg_price,
                        sale_price: variant.sale_price,
                        sku_variation: variant.sku_variation,
                        attributes: variant.attributes ?? [],
                        color: variant.color ?? '',
                        ring_size: variant.ring_size ?? '',
                    })),
                }));
                setProducts(formattedProduct);
            });
    }, []);

    async function handleDownloadExcel(data: any, sheetName: string, header: string[], fileName: string) {
        const XLSX = await import('xlsx');
        const flattenedData: any[] = [];
        const merges: any[] = [];

        let rowIndex = 1;

        data.forEach((product: any) => {
            // Jika product_variation adalah array, gunakan langsung. Jika bukan, ubah ke array dengan 1 objek
            const variations = Array.isArray(product.product_variation)
                ? product.product_variation
                : product.product_variation
                ? [
                      {
                          sku_variation: product.product_variation,
                          reg_price: product.variation_reg_price,
                          sale_price: product.variation_sale_price,
                          attributes: product.attributes ?? [],
                      },
                  ]
                : [];

            if (variations.length > 0) {
                variations.forEach((variant: any, index: number) => {
                    flattenedData.push({
                        product_sku: product.product_sku,
                        product_title: product.product_title ?? '', // Beri nilai default jika kosong
                        product_reg_price: product.product_reg_price,
                        product_sale_price: product.product_sale_price,
                        sku_variation: variant.sku_variation,
                        ring_size: getRingSize(variant),
                        color: getColor(variant),
                        variation_reg_price: variant.reg_price,
                        variation_sale_price: variant.sale_price,
                    });

                    if (index === 0 && variations.length > 1) {
                        merges.push({
                            s: { r: rowIndex, c: 0 },
                            e: { r: rowIndex + variations.length - 1, c: 0 },
                        });
                    }
                    rowIndex++;
                });
            } else {
                flattenedData.push({
                    product_sku: product.product_sku,
                    product_title: product.product_title ?? '',
                    product_reg_price: product.product_reg_price,
                    product_sale_price: product.product_sale_price,
                    sku_variation: '',
                    ring_size: '',
                    color: '',
                    variation_reg_price: '',
                    variation_sale_price: '',
                });
                rowIndex++;
            }
        });

        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(flattenedData);

        XLSX.utils.sheet_add_aoa(worksheet, [header], { origin: 'A1' });

        // Fungsi pengelompokan data berdasarkan product_sku
        // worksheet['!merges'] = merges;

        XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
        XLSX.writeFile(workbook, fileName + '.xlsx', { compression: true });
    }

    const [bulkPricing, setBulkPricing] = useState<Product[]>([]);

    const [importFileName, setImportFileName] = useState<string>('');
    const [isImporting, setIsImporting] = useState<boolean>(false);
    const [isFetching, setIsFetching] = useState<boolean>(false);
    const [isLoading, setIsLoading] = useState<boolean>(false);

    const handleUploadClick = () => {
        const fileInput = document.getElementById('import-excel'); // Locate the input element by id
        if (fileInput) {
            fileInput.click(); // Trigger the click event for the input element
        }
    };
    const handleUpload = (e: any) => {
        const file = e.target.files?.[0];
        if (!file) return;

        setImportFileName(file.name);
        setIsImporting(true);

        const reader = new FileReader();

        reader.onload = async (e) => {
            const binaryData = e.target?.result as string;

            if (!binaryData) return;

            try {
                const XLSX = await import('xlsx');
                const workbook = XLSX.read(binaryData, { type: 'binary' });
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];
                const data = XLSX.utils.sheet_to_json(worksheet);

                setIsImporting(false);

                if (!data || data.length === 0) {
                    coloredToast('warning', 'No data found in the Excel file');
                    return;
                }

                // Gabungkan data berdasarkan product_sku
                const groupedProducts: any = data.reduce((acc: any, item: any) => {
                    const existing = acc.find((p: any) => p.product_sku === item.product_sku);

                    const variation = {
                        variation_sku: item.product_variation,
                        variation_reg_price: item.variation_reg_price ?? 0,
                        variation_sale_price: item.variation_sale_price ?? 0,
                    };

                    if (existing) {
                        if (variation.variation_sku) {
                            existing.variations.push(variation);
                        }
                    } else {
                        acc.push({
                            product_sku: item.product_sku,
                            variation_price_change: item.variation_price_change,
                            product_reg_price: item.product_reg_price ?? 0,
                            product_sale_price: item.product_sale_price ?? 0,
                            variations: variation.variation_sku ? [variation] : [],
                        });
                    }

                    return acc;
                }, []);

                const listProductSKU = groupedProducts.map((product: any) => product.product_sku);
                if (listProductSKU.length === 0) {
                    coloredToast('warning', 'Product SKU not available');
                    return;
                }

                const products = await fetchingDataImport(listProductSKU);

                const listImporting = products.map((product: any) => {
                    const matchProductImport = groupedProducts.find((prod: any) => prod.product_sku === product.product_sku);

                    return {
                        id: product.id,
                        product_sku: product.product_sku,
                        product_title: product.product_title,
                        variation_price_change: matchProductImport.variation_price_change?.toString() ?? '1',
                        product_reg_price: matchProductImport.product_reg_price,
                        product_sale_price: matchProductImport.product_sale_price,
                        variations: matchProductImport.variations,
                    };
                });

                setBulkPricing(listImporting);
            } catch (error) {
                console.error(error);
                coloredToast('danger', 'Something went wrong while processing the Excel file');
                setIsImporting(false);
            }
        };

        reader.readAsBinaryString(file);
    };

    async function fetchingDataImport(data: any) {
        setIsFetching(true);

        try {
            const api_url = process.env.API_URL;
            const payload = {
                data,
            };

            const response = await fetch(`${api_url}api/products/product-list-sku`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });
            const res = await response.json();

            if (!response.ok) {
                coloredToast('warning', res.message);
                setIsFetching(false);
                return [];
            }

            coloredToast('success', 'Importing and fetching data successfully');
            setIsFetching(false);

            return res.products;
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'Something went wrong while making the API request');
        }
        setIsFetching(false);
        return [];
    }

    const [filteredItems, setFilteredItems] = useState<any>(bulkPricing);

    const [search, setSearch] = useState('');

    useEffect(() => {
        const filteredProducts = bulkPricing.filter((product) => product.product_title.toLowerCase().includes(search.toLowerCase()));
        setFilteredItems(filteredProducts);
    }, [search]);

    const deleteProduct = (product: any = null) => {
        setBulkPricing(bulkPricing.filter((d: any) => d.id !== product.id));
        showMessage('Product ' + product.product_title + ' has been deleted successfully.');
    };
    useEffect(() => {
        setFilteredItems(bulkPricing);
    }, [bulkPricing]);

    const showMessage = (msg = '', type = 'success') => {
        const toast: any = Swal.mixin({
            toast: true,
            position: 'top',
            showConfirmButton: false,
            timer: 3000,
            customClass: { container: 'toast' },
        });
        toast.fire({
            icon: type,
            title: msg,
            padding: '10px 20px',
        });
    };

    const [batchSaving, setBatchSaving] = useState(0);

    const handleSaveBulk = async () => {
        setBatchSaving(0);
        if (bulkPricing.length <= 0) {
            coloredToast('warning', 'no item available');
            return;
        }

        Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            showCancelButton: true,
            confirmButtonText: 'Bulk',
            padding: '2em',
            customClass: {
                container: 'sweet-alerts',
            },
        }).then(async (result) => {
            if (result.value) {
                setIsLoading(true);

                const api_url = process.env.API_URL;
                const batchSize = 10;
                const totalItems = bulkPricing.length;
                const batches: any[] = [];

                for (let i = 0; i < totalItems; i += batchSize) {
                    const batch = bulkPricing.slice(i, i + batchSize);
                    batches.push(batch);
                }

                const requests = batches.map(async (batch) => {
                    try {
                        const payload = {
                            data: batch,
                        };

                        const response = await fetch(`${api_url}api/products/bulk-update-price`, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(payload),
                            credentials: 'include',
                        });

                        if (!response.ok) {
                            const res = await response.json();
                            throw new Error(res.message);
                        }
                        setBatchSaving((prev) => prev + batch.length);
                        await logActivity({
                            location: 'Bulk Pricing',
                            description: `Bulk pricing - ${batch.length} products updated successfully`,
                        });
                        return 'Bulk updated successfully';
                    } catch (error: any) {
                        await logActivity({
                            location: 'Bulk Pricing',
                            description: `Gagal mengubah Product dengan harga emas`,
                        });
                        throw new Error(`Something went wrong while updating bulk: ${error.message}`);
                    }
                });

                try {
                    const settled = await Promise.allSettled(requests);
                    let successCount = 0;
                    let failedCount = 0;

                    settled.forEach((item, index) => {
                        const count = batches[index].length;
                        if (item.status === 'fulfilled') {
                            successCount += count;
                        } else {
                            failedCount += count;
                            console.error(item.reason);
                        }
                    });

                    setIsLoading(false);

                    if (failedCount === 0) {
                        coloredToast('success', `${successCount} produk berhasil diperbarui`);
                    } else if (successCount === 0) {
                        coloredToast('danger', `${failedCount} produk gagal diperbarui`);
                    } else {
                        coloredToast('warning', `${successCount} produk berhasil diperbarui, ${failedCount} produk gagal diperbarui`);
                    }
                } catch (error) {
                    console.error(error);
                    coloredToast('danger', 'Something went wrong while processing the requests.');
                    setIsLoading(false);
                }
            }
        });
    };

    const [expandedRows, setExpandedRows] = useState<number[]>([]);

    const toggleRow = (id: number) => {
        setExpandedRows((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]));
    };

    return (
        <>
                {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <Link href="/products" className="text-primary hover:underline">
                                        Products
                                    </Link>
                                </li>
                                <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                                    <span>Bulk pricing</span>
                                </li>
                            </ul>
                        </div>
                        <div className="mb-2 mt-5 flex items-center justify-between gap-2">
                            <div className="flex items-center">
                                <input type="file" style={{ display: 'none' }} accept=".xls, .xlsx" id="import-excel" onChange={(e) => handleUpload(e)} />
                                <button onClick={handleUploadClick} className="btn-sm btn btn-outline-success gap-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none">
                                        <path
                                            d="M15.3929 4.05365L14.8912 4.61112L15.3929 4.05365ZM19.3517 7.61654L18.85 8.17402L19.3517 7.61654ZM21.654 10.1541L20.9689 10.4592V10.4592L21.654 10.1541ZM3.17157 20.8284L3.7019 20.2981H3.7019L3.17157 20.8284ZM20.8284 20.8284L20.2981 20.2981L20.2981 20.2981L20.8284 20.8284ZM14 21.25H10V22.75H14V21.25ZM2.75 14V10H1.25V14H2.75ZM21.25 13.5629V14H22.75V13.5629H21.25ZM14.8912 4.61112L18.85 8.17402L19.8534 7.05907L15.8947 3.49618L14.8912 4.61112ZM22.75 13.5629C22.75 11.8745 22.7651 10.8055 22.3391 9.84897L20.9689 10.4592C21.2349 11.0565 21.25 11.742 21.25 13.5629H22.75ZM18.85 8.17402C20.2034 9.3921 20.7029 9.86199 20.9689 10.4592L22.3391 9.84897C21.9131 8.89241 21.1084 8.18853 19.8534 7.05907L18.85 8.17402ZM10.0298 2.75C11.6116 2.75 12.2085 2.76158 12.7405 2.96573L13.2779 1.5653C12.4261 1.23842 11.498 1.25 10.0298 1.25V2.75ZM15.8947 3.49618C14.8087 2.51878 14.1297 1.89214 13.2779 1.5653L12.7405 2.96573C13.2727 3.16993 13.7215 3.55836 14.8912 4.61112L15.8947 3.49618ZM10 21.25C8.09318 21.25 6.73851 21.2484 5.71085 21.1102C4.70476 20.975 4.12511 20.7213 3.7019 20.2981L2.64124 21.3588C3.38961 22.1071 4.33855 22.4392 5.51098 22.5969C6.66182 22.7516 8.13558 22.75 10 22.75V21.25ZM1.25 14C1.25 15.8644 1.24841 17.3382 1.40313 18.489C1.56076 19.6614 1.89288 20.6104 2.64124 21.3588L3.7019 20.2981C3.27869 19.8749 3.02502 19.2952 2.88976 18.2892C2.75159 17.2615 2.75 15.9068 2.75 14H1.25ZM14 22.75C15.8644 22.75 17.3382 22.7516 18.489 22.5969C19.6614 22.4392 20.6104 22.1071 21.3588 21.3588L20.2981 20.2981C19.8749 20.7213 19.2952 20.975 18.2892 21.1102C17.2615 21.2484 15.9068 21.25 14 21.25V22.75ZM21.25 14C21.25 15.9068 21.2484 17.2615 21.1102 18.2892C20.975 19.2952 20.7213 19.8749 20.2981 20.2981L21.3588 21.3588C22.1071 20.6104 22.4392 19.6614 22.5969 18.489C22.7516 17.3382 22.75 15.8644 22.75 14H21.25ZM2.75 10C2.75 8.09318 2.75159 6.73851 2.88976 5.71085C3.02502 4.70476 3.27869 4.12511 3.7019 3.7019L2.64124 2.64124C1.89288 3.38961 1.56076 4.33855 1.40313 5.51098C1.24841 6.66182 1.25 8.13558 1.25 10H2.75ZM10.0298 1.25C8.15538 1.25 6.67442 1.24842 5.51887 1.40307C4.34232 1.56054 3.39019 1.8923 2.64124 2.64124L3.7019 3.7019C4.12453 3.27928 4.70596 3.02525 5.71785 2.88982C6.75075 2.75158 8.11311 2.75 10.0298 2.75V1.25Z"
                                            fill="currentColor"
                                        />
                                        <path d="M13 2.5V5C13 7.35702 13 8.53553 13.7322 9.26777C14.4645 10 15.643 10 18 10H22" stroke="currentColor" strokeWidth="1.5" />
                                        <path d="M8.5 18.5L8.5 13.5M8.5 13.5L6.5 15.375M8.5 13.5L10.5 15.375" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                    Import Data Product .xlsx
                                </button>
                                <span className="mx-2">{importFileName}</span>
                            </div>
                            <div className="dropdown">
                                <button type="button" className="btn btn-sm btn-outline-primary" onClick={() => handleDownloadExcel(products, 'Products', headerProducts, 'List Products')}>
                                    Download List
                                </button>
                            </div>
                        </div>
                        <div className="panel mt-4">
                            <div className="my-2 flex justify-between">
                                <input type="text" className="form-input w-auto" placeholder="Search Product Name" value={search} onChange={(e) => setSearch(e.target.value)} />
                                <div className="flex items-center">
                                    {isLoading && (
                                        <span className="mx-2">
                                            saving ({batchSaving}/{bulkPricing.length})
                                        </span>
                                    )}
                                    <button type="button" disabled={isLoading} onClick={handleSaveBulk} className="btn btn-success w-fit 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 Bulk
                                    </button>
                                </div>
                            </div>
                            <div className="mb-8 mt-4 table w-full">
                                <table className="w-full border-collapse" border={1}>
                                    <thead>
                                        <tr>
                                            <th>No</th>
                                            <th></th>
                                            <th>SKU</th>
                                            <th>Title</th>
                                            <th>Reg Price</th>
                                            <th>Sale Price</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {(isImporting || isFetching) && (
                                            <tr>
                                                <td colSpan={5} className="!text-center font-semibold">
                                                    <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>

                                                    <span className="mx-2">
                                                        {isImporting && 'importing file'}
                                                        {isFetching && 'fetching data'}
                                                    </span>
                                                </td>
                                            </tr>
                                        )}
                                        {!isImporting && !isFetching && filteredItems.length <= 0 && (
                                            <tr>
                                                <td colSpan={5} className="!text-center font-semibold">
                                                    No Item Available
                                                </td>
                                            </tr>
                                        )}
                                        {!isImporting &&
                                            !isFetching &&
                                            filteredItems.map((product: any, key: number) => (
                                                <Fragment key={product.id}>
                                                    <tr>
                                                        <td className="mx-2 text-center">{key + 1}</td>
                                                        <td>
                                                            {product.variations?.length > 0 && (
                                                                <button type="button" className="toggle-btn" onClick={() => toggleRow(product.id)}>
                                                                    {expandedRows.includes(product.id) ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
                                                                </button>
                                                            )}
                                                        </td>
                                                        <td className="mx-2">
                                                            <input type="text" readOnly className=" form-input w-2/3  lg:w-[150px]" name="product_sku" id="product_sku" value={product.product_sku} />
                                                        </td>
                                                        <td className="mx-2">
                                                            <input
                                                                type="text"
                                                                readOnly
                                                                className="form-input w-2/3  lg:w-[250px]"
                                                                name="product_title"
                                                                id="product_title"
                                                                value={product.product_title}
                                                            />
                                                        </td>
                                                        <td className="mx-2">
                                                            <NumberFormatter
                                                                className="form-input w-2/3  lg:w-[120px]"
                                                                name="product_reg_price"
                                                                value={product.product_reg_price}
                                                                onChange={(value) => {
                                                                    const updatedItems = bulkPricing.map((item) => {
                                                                        if (item.id === product.id) {
                                                                            return {
                                                                                ...item,
                                                                                product_reg_price: value,
                                                                            };
                                                                        }
                                                                        return item;
                                                                    });
                                                                    setBulkPricing(updatedItems);
                                                                }}
                                                            />
                                                        </td>
                                                        <td className="mx-2">
                                                            <NumberFormatter
                                                                className="form-input w-2/3  lg:w-[120px]"
                                                                name="product_sale_price"
                                                                value={product.product_sale_price}
                                                                onChange={(value) => {
                                                                    const updatedItems = bulkPricing.map((item) => {
                                                                        if (item.id === product.id) {
                                                                            return {
                                                                                ...item,
                                                                                product_sale_price: value,
                                                                            };
                                                                        }
                                                                        return item;
                                                                    });
                                                                    setBulkPricing(updatedItems);
                                                                }}
                                                            />
                                                        </td>

                                                        <td>
                                                            <button type="button" className="btn btn-sm btn-outline-danger" onClick={() => deleteProduct(product)}>
                                                                Delete
                                                            </button>
                                                        </td>
                                                    </tr>
                                                    {product.variations?.length > 0 && expandedRows.includes(product.id) && (
                                                        <Fragment>
                                                            <tr className="child-row">
                                                                <td colSpan={8} className="ml-24 text-left font-bold">
                                                                    Variation {product.product_title}
                                                                </td>
                                                            </tr>
                                                            <tr>
                                                                <td className="font-semibold">No.</td>
                                                                <td colSpan={2} className="mx-2 font-semibold">
                                                                    SKU
                                                                </td>
                                                                <td className="mx-2 font-semibold">Regular Price</td>
                                                                <td className="mx-2 font-semibold">Sale Price</td>
                                                            </tr>
                                                            {product.variations.map((variation: any, i: number) => (
                                                                <Fragment key={i}>
                                                                    <tr>
                                                                        <td className="mx-2">{i + 1}</td>
                                                                        <td className="mx-2" colSpan={2}>
                                                                            <input type="text" className="form-input w-2/3 lg:w-[250px]" readOnly value={variation.variation_sku} />
                                                                        </td>
                                                                        <td className="mx-2">
                                                                            <NumberFormatter
                                                                                className="form-input w-2/3 lg:w-[120px]"
                                                                                value={variation.variation_reg_price}
                                                                                onChange={(value) => {
                                                                                    const updatedItems = bulkPricing.map((item) => {
                                                                                        if (item.id === product.id) {
                                                                                            const updatedVariations = item.variations?.map((v: Variation) =>
                                                                                                v.variation_sku === variation.variation_sku ? { ...v, variation_reg_price: value } : v
                                                                                            );
                                                                                            return { ...item, variations: updatedVariations };
                                                                                        }
                                                                                        return item;
                                                                                    });
                                                                                    setBulkPricing(updatedItems);
                                                                                }}
                                                                            />
                                                                        </td>
                                                                        <td className="mx-2">
                                                                            <NumberFormatter
                                                                                className="form-input w-2/3 lg:w-[120px]"
                                                                                value={variation.variation_sale_price}
                                                                                onChange={(value) => {
                                                                                    const updatedItems = bulkPricing.map((item) => {
                                                                                        if (item.id === product.id) {
                                                                                            const updatedVariations = item.variations?.map((v: Variation) =>
                                                                                                v.variation_sku === variation.variation_sku ? { ...v, variation_sale_price: value } : v
                                                                                            );
                                                                                            return { ...item, variations: updatedVariations };
                                                                                        }
                                                                                        return item;
                                                                                    });
                                                                                    setBulkPricing(updatedItems);
                                                                                }}
                                                                            />
                                                                        </td>
                                                                    </tr>
                                                                </Fragment>
                                                            ))}
                                                        </Fragment>
                                                    )}
                                                </Fragment>
                                            ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </>
                )}
        </>
    );
};
export default BulkPricing;
