import { useEffect, useState } from 'react';
import { coloredToast } from '@/lib/toast';
import NumberFormatter from '@/lib/ribuan';
import { logActivity } from '@/utils/activityLogger';
interface ProductListGramasi {
    id: number;
    char: string;
    gr: number;
}

interface SettingProductScript {
    gr_kalung: number;
    gr_gelang: number;
    pengali_lotus: number;
    pengali_aurum: number;
    harga_emas: number;
    discount: number;
    discount_gelang: number;
}
const ProductScript = () => {
    const [lists, setLists] = useState<ProductListGramasi[]>([]);
    const [isLoading, setIsLoading] = useState(false);

    const [initialConfigScript, setInitialConfigScript] = useState<SettingProductScript | null>(null);
    const [initialLists, setInitialLists] = useState<ProductListGramasi[]>([]);


    const [configScript, setConfigScript] = useState<SettingProductScript>({
        gr_kalung: 0,
        gr_gelang: 0,
        pengali_lotus: 0,
        pengali_aurum: 0,
        harga_emas: 0,
        discount: 0,
        discount_gelang: 0,
    });

    const addList = () => {
        let maxId = 0;
        maxId = lists?.length ? lists.reduce((max: number, character: any) => (character.id > max ? character.id : max), lists[0].id) : 0;

        setLists([
            ...lists,
            {
                id: maxId + 1,
                char: '',
                gr: 0,
            },
        ]);
    };

    const getScriptChangesDescription = () => {
        const changes: string[] = [];
    
        if (initialConfigScript) {
            Object.keys(configScript).forEach((key) => {
                const oldVal = initialConfigScript[key as keyof SettingProductScript];
                const newVal = configScript[key as keyof SettingProductScript];
                if (oldVal !== newVal) {
                    changes.push(`${key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}: ${oldVal} -> ${newVal}`);
                }
            });
        }
    
        const changedList = lists.filter((list) => {
            const initial = initialLists.find((i) => i.id === list.id);
            return !initial || initial.char !== list.char || initial.gr !== list.gr;
        });
    
        changedList.forEach((list) => {
            const initial = initialLists.find((i) => i.id === list.id);
            if (!initial) {
                changes.push(`Added Character ${list.char} (${list.gr}gr)`);
            } else {
                if (initial.char !== list.char) {
                    changes.push(`Character ID ${list.id} Char: ${initial.char} -> ${list.char}`);
                }
                if (initial.gr !== list.gr) {
                    changes.push(`Character ID ${list.id} Gram: ${initial.gr} -> ${list.gr}`);
                }
            }
        });
    
        initialLists.forEach((initItem) => {
            if (!lists.find((l) => l.id === initItem.id)) {
                changes.push(`Removed Character ${initItem.char} (${initItem.gr}gr)`);
            }
        });
    
        return changes.length ? changes.join(' | ') : 'No changes made.';
    };
    

    const fetchData = async () => {
        try {
            const api_url = process.env.API_URL;

            // login credential
            const response = await fetch(`${api_url}api/setting/script-list`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },

                credentials: 'include', // Include this option
            });

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

            setConfigScript(res.product_script_setting);
            setInitialConfigScript(res.product_script_setting);
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'somthing went wrong');
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const removeList = (item: any = null) => {
        setLists(lists.filter((d: any) => d.id !== item.id));
    };

    const changeList = (type: string, value: any, id: number) => {
        const updatedList = lists.map((list) => {
            if (list.id === id) {
                return {
                    ...list,
                    [type === 'char' ? 'char' : 'gr']: type === 'gr' ? Number(value) : value,
                };
            }
            return list;
        });

        setLists(updatedList);
    };

    const saveScript = async () => {
        const filteredList = lists.filter((list) => list.char);
        if (filteredList.length <= 0) {
            coloredToast('warning', 'Please add at least 1 item');
            return;
        }
        if (hasDuplicateChars(filteredList)) {
            coloredToast('warning', "Duplicate 'character' values found. Cannot submit.");
            return;
        }

        if (configScript.gr_kalung < 0 || configScript.pengali_lotus < 0 || configScript.pengali_aurum < 0 || configScript.harga_emas < 0 || configScript.discount < 0) {
            coloredToast('warning', 'Setting has value under 0');
            return;
        }
        if (configScript.pengali_lotus > 100) {
            coloredToast('warning', 'Pengali Lotus more than 100%');
            return;
        }
        if (configScript.discount > 100) {
            coloredToast('warning', 'Discount more than 100%');
            return;
        }

        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const payload = {
                list: filteredList,
                config: configScript,
            };

            // login credential
            const response = await fetch(`${api_url}api/setting/script-list/update`, {
                method: 'PATCH',
                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;
            }

            const description = getScriptChangesDescription();
            
            await logActivity({
                location: 'Product Script',
                description: `Product Script - Updated: ${description}`,
            });
            coloredToast('success', 'Script updated successfully');
        } catch (error) {
            console.error(error);
            await logActivity({
                location: 'Product Script',
                description: `Product Script - gagal di update`,
            });
            coloredToast('danger', 'somthing went wrong');
        }

        setIsLoading(false);
    };

    return (
        <>
            <div className="flex flex-col gap-2.5 xl:flex-row">
                <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 ">
                            <div className="text-lg">List Gr Character Script :</div>
                            <div className="mb-4 mt-4 w-full ">
                                <div className="mb-8 mt-2 table w-full">
                                    <table>
                                        <thead>
                                            <tr>
                                                <th>Character</th>
                                                <th>Gram</th>
                                                <th></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {lists.length <= 0 && (
                                                <tr>
                                                    <td colSpan={2} className="!text-center font-semibold">
                                                        No List Available
                                                    </td>
                                                </tr>
                                            )}
                                            {lists.map((list: any) => {
                                                return (
                                                    <tr className="align-top" key={list.id}>
                                                        <td>
                                                            <input
                                                                type="text"
                                                                className="form-input w-full"
                                                                placeholder="a"
                                                                maxLength={1}
                                                                value={list.char}
                                                                onChange={(e) => changeList('char', e.target.value, list.id)}
                                                            />
                                                        </td>
                                                        <td>
                                                            <input
                                                                type="number"
                                                                className="form-input w-full"
                                                                placeholder="gram"
                                                                value={list.gr}
                                                                onChange={(e) => changeList('gr', e.target.value, list.id)}
                                                            />
                                                        </td>

                                                        <td>
                                                            <button type="button" onClick={() => removeList(list)}>
                                                                <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="m-4">
                                        <button type="button" className="btn btn-outline-primary btn-sm" onClick={() => addList()}>
                                            Add List
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="mb-4 w-full lg:w-1/2 lg:max-w-fit">
                            <div className="text-lg">Setting Script :</div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="billing_name" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Gramasi Kalung (gr)
                                </label>
                                <input
                                    id="gr_kalung"
                                    type="number"
                                    name="gr_kalung"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.gr_kalung}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            gr_kalung: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="billing_name" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Gramasi Gelang (gr)
                                </label>
                                <input
                                    id="gr_gelang"
                                    type="number"
                                    name="gr_gelang"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.gr_gelang}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            gr_gelang: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="pengali_lotus" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Pengali Lotus (%)
                                </label>
                                <input
                                    id="pengali_lotus"
                                    type="number"
                                    name="pengali_lotus"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.pengali_lotus}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            pengali_lotus: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="pengali_aurum" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Pengali Aurum
                                </label>
                                <input
                                    id="pengali_aurum"
                                    type="number"
                                    name="pengali_aurum"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.pengali_aurum}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            pengali_aurum: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="harga_emas" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Harga Emas
                                </label>
                                <NumberFormatter
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder="Harga Emas"
                                    value={configScript.harga_emas}
                                    onChange={(value: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            harga_emas: value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="discount" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Discount Kalung (%)
                                </label>
                                <input
                                    id="discount"
                                    type="number"
                                    name="discount"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.discount}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            discount: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <div className="mt-4 flex items-center">
                                <label htmlFor="discount" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Discount Gelang (%)
                                </label>
                                <input
                                    id="discount_gelang"
                                    type="number"
                                    name="discount_gelang"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder=""
                                    value={configScript.discount_gelang}
                                    onChange={(e: any) =>
                                        setConfigScript((config: SettingProductScript) => ({
                                            ...config,
                                            discount_gelang: e.target.value,
                                        }))
                                    }
                                />
                            </div>
                            <button type="button" disabled={isLoading} onClick={saveScript} className="btn btn-success mt-4 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>
            </div>
        </>
    );
};
export default ProductScript;
// Function to check for duplicate "char" values
function hasDuplicateChars(lists: any) {
    const charSet = new Set();
    for (const item of lists) {
        if (item.char && charSet.has(item.char)) {
            return true; // Duplicate "char" found
        }
        charSet.add(item.char);
    }
    return false; // No duplicates found
}
