import { setPageTitle } from '@/store/themeConfigSlice';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Link from 'next/link';
import { useRouter } from 'next/router';
import Swal from 'sweetalert2';
import { coloredToast } from '@/lib/toast';
import Select from 'react-select';
import NumberFormatter from '@/lib/ribuan';
import { logActivity } from '@/utils/activityLogger';

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

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

    const router = useRouter();

    const listCategories = [
        { value: '6k', label: '6k' },
        { value: '6k sni', label: '6k SNI' },
    ];

    const [selectCategory, setSelectCategory] = useState<any>();
    const [isFetching, setIsFetching] = useState(false);

    const [data, setData] = useState<[]>([]);
    const handleCategoryChange = (e: any) => {
        setSelectCategory(e);
    };

    const handleFetchProductCat = async () => {
        if (!selectCategory) {
            coloredToast('warning', 'Category must be selected');
            return;
        }

        setIsFetching(true);
        try {
            const category = selectCategory.value;
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/product-list-cat/?cat=${category}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const res = await response.json();

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

            coloredToast('success', 'Fetching data success');
            setIsFetching(false);
            setData(res.products);
            return;
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'Something went wrong while fetching data');
        }
        setIsFetching(false);
        setData([]);
        return;
    };

    const [goldPrice, setGoldPrice] = useState(0);

    const handleSetGoldPrice = () => {
        coloredToast('success', 'Preview Regular Price with Gold Price successfully');
        const updatedData: any = data.map((list: any) => {
            const product_items = list.product_items;
            if (product_items.length > 0) {
                product_items.map((item: any) => {
                    const newReg = Math.round(goldPrice * item.gold_weight);
                    item.reg_price = newReg;
                    item.sale_price = 0;
                    return item;
                });
            } else {
                const newReg = Math.round(goldPrice * list.product_gold_weight);
                list.product_reg_price = newReg;
                list.product_sale_price = 0;
            }
            return list;
        });

        setData(updatedData);
    };

    const [isLoading, setIsLoading] = useState(false);
    const handleSaveBulk = async () => {
        if (!goldPrice) {
            coloredToast('warning', 'Gold price not set');
            return;
        }
        if (window.confirm('Are you sure want to update selected product category with calculating gold price ?')) {
            setIsLoading(true);
            try {
                const api_url = process.env.API_URL;
                const payload = {
                    category: selectCategory.value,
                    goldPrice,
                };
                const response = await fetch(`${api_url}api/products/product-list-cat/update`, {
                    method: 'PATCH',
                    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);
                    setIsLoading(false);
                    return;
                }
            } catch (error) {
                console.error(error);
                setIsLoading(false);
                coloredToast('danger', 'Something went wrong');
                await logActivity({
                    location: 'Bulk Gold Price',
                    description: `Gagal mengubah Product dengan harga emas`,
                });
            }
            coloredToast('success', 'Updated Product with Gold Price Successfully');
            await logActivity({
                location: 'Bulk Gold Price',
                description: `Updated Product with Gold Price Successfully`,
            });
            setIsLoading(false);
            router.push('/products');
        }
    };
    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 with gold pricing</span>
                                </li>
                            </ul>
                        </div>
                        <div className="mb-5 flex">
                            <div className="custom-select w-1/2 lg:w-1/4">
                                <Select
                                    options={listCategories}
                                    id="category_select"
                                    className="dark:flex-1"
                                    name="product_type"
                                    value={selectCategory}
                                    onChange={handleCategoryChange}
                                    placeholder="Select category"
                                />
                            </div>
                            <button type="button" className="btn btn-success mx-2" onClick={handleFetchProductCat}>
                                {isFetching ? (
                                    <>
                                        <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>Getting data ...</span>
                                    </>
                                ) : (
                                    <>Browse</>
                                )}
                            </button>
                        </div>
                        {data.length > 0 && (
                            <>
                                <div className="mb-5 flex">
                                    <NumberFormatter className="form-input w-1/2 lg:w-1/4" placeholder="masukkan harga emas" value={goldPrice} onChange={(value: any) => setGoldPrice(Number(value))} />
                                    <button className="btn btn-primary mx-2" onClick={handleSetGoldPrice}>
                                        Preview
                                    </button>
                                </div>
                                <div>
                                    <button type="button" disabled={isLoading} onClick={handleSaveBulk} className="btn btn-success mb-5 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>
                                        )}
                                        Set Bulk
                                    </button>
                                </div>
                            </>
                        )}

                        <div className="panel">
                            <div className=" text-center font-bold"> PREVIEW </div>
                            <div className="mb-8 mt-4 table w-full">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Title</th>
                                            <th>SKU / SKU variation</th>
                                            <th>Gold Weight (gr)</th>
                                            <th>Reg Price</th>
                                            <th>Sale Price</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {data.length <= 0 && (
                                            <tr>
                                                <td colSpan={5} className="!text-center font-semibold">
                                                    No Item Available
                                                </td>
                                            </tr>
                                        )}
                                        {data.map((list: any, listIndex: number) => {
                                            const product_items = list.product_items;
                                            if (product_items.length > 0) {
                                                return product_items.map((item: any, itemIndex: number) => (
                                                    <tr className=" align-middle" key={`${list.id || listIndex}-${item.id || itemIndex}`}>
                                                        <td className="mx-2">{list.product_title}</td>
                                                        <td className="mx-2">{item.sku_variation || list.product_sku}</td>
                                                        <td className="mx-2">{item.gold_weight} gr</td>
                                                        <td className="mx-2">Rp {item.reg_price.toLocaleString('id-ID')}</td>
                                                        <td className="mx-2">Rp {item.sale_price.toLocaleString('id-ID')}</td>
                                                    </tr>
                                                ));
                                            } else {
                                                return (
                                                    <tr className=" align-middle" key={`${list.id || listIndex}-no-items`}>
                                                        <td className="mx-2">{list.product_title}</td>
                                                        <td className="mx-2">{list.product_sku}</td>
                                                        <td className="mx-2">{list.product_gold_weight} gr</td>
                                                        <td className="mx-2">Rp {list.product_reg_price.toLocaleString('id-ID')}</td>
                                                        <td className="mx-2">Rp {list.product_sale_price.toLocaleString('id-ID')}</td>
                                                    </tr>
                                                );
                                            }
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </>
                )}
        </>
    );
};
export default BulkGoldPrice;
