import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/flatpickr.css';
import Select from 'react-select';
import { getCouponCategories } from '@/lib/coupon-categories';
import { useEffect, useState } from 'react';
import { SaveCoupon } from '@/utils/saveCoupon';
import { useRouter } from 'next/router';
import { coloredToast } from '@/lib/toast';
import NumberFormatter from '@/lib/ribuan';
import { logActivity } from '@/utils/activityLogger';
import ProductCategorySelector from '@/components/Shared/ProductCategorySelector';
import CouponVoucherPreview from '@/components/Coupons/CouponVoucherPreview';
import FreeItemProductSelector from '@/components/Promotions/FreeItemProductSelector';
import Swal from 'sweetalert2';
import Tooltip from '@mui/material/Tooltip';
import InfoIcon from '@mui/icons-material/Info';

interface Coupon {
    id: string;
    coupon_name: string;
    coupon_title: string;
    coupon_description: string;
    coupon_type: string;
    coupon_amount: number;
    coupon_start_date: Date | string | null;
    coupon_end_date: Date | string | null;
    coupon_is_individual: boolean;
    coupon_is_limited: boolean;
    coupon_limit: number;
    coupon_categories: string[];
    include_product_categories: string[];
    exclude_product_categories: string[];
    coupon_min_purchase: number;
    coupon_is_max_disc: boolean;
    coupon_max_amount_disc: number;
    coupon_free_item_name: string;
    coupon_free_item_products: string[];
    coupon_is_unique_user: boolean;
    coupon_is_noticed: boolean;
    coupon_notice_desc: string;
    coupon_is_highlight: boolean;
    excluded_products: string[];
    included_products: string[];
    coupon_is_public: boolean;
}

interface CouponFormProps {
    couponForm: Coupon;
    setCouponForm: React.Dispatch<React.SetStateAction<Coupon>>;
    isCreate: boolean;
    isUpdate: boolean;
}

const CouponForm: React.FC<CouponFormProps> = ({ couponForm, setCouponForm, isUpdate, isCreate }) => {
    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        const { name } = e.target;
        const value = name === 'coupon_name' ? e.target.value.toUpperCase() : e.target.value;

        // Jika yang diubah adalah coupon_type
        if (name === 'coupon_type') {
            setCouponForm((prev) => ({
                ...prev,
                coupon_type: value,
                coupon_amount: value === 'free_item' ? 0 : prev.coupon_amount,
                coupon_free_item_name: value !== 'free_item' ? '' : prev.coupon_free_item_name,
                coupon_free_item_products: value !== 'free_item' ? [] : prev.coupon_free_item_products || [],
            }));
        } else {
            setCouponForm((prev) => ({
                ...prev,
                [name]: value,
            }));
        }
    };

    const [couponCategories, setCouponCategories] = useState<any[]>([]);
    const [initialCouponForm, setInitialCouponForm] = useState<any | null>(null);

    const router = useRouter();

    const fetchCouponCategories = async () => {
        const resCouponCat = await getCouponCategories();
        const formattedOption = Array.isArray(resCouponCat)
            ? resCouponCat.map((option: string) => ({
                  value: option,
                  label: option.charAt(0).toUpperCase() + option.slice(1),
              }))
            : [];
        setCouponCategories(formattedOption);
    };

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

    useEffect(() => {
        if (isUpdate) {
            setInitialCouponForm(JSON.parse(JSON.stringify(couponForm)));
        }
    }, [isUpdate]);

    const setStartDate = (date: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_start_date: date,
            };
        });
    };
    const setEndDate = (date: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_end_date: date,
            };
        });
    };

    const changeIsLimit = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_limited: e.target.checked,
            };
        });
    };
    const changeIsIndividual = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_individual: e.target.checked,
            };
        });
    };
    const changeIsUniqueUser = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_unique_user: e.target.checked,
            };
        });
    };
    const changeIsNoticed = (e: any) => {
        const checked = e.target.checked;
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_noticed: checked,
                coupon_end_date: checked ? prev.coupon_end_date : null,
            };
        });
    };
    const changeIsMaxDisc = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_max_disc: e.target.checked,
            };
        });
    };
    const changeIsHighlight = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_highlight: e.target.checked,
            };
        });
    };
    const changeIsPublic = (e: any) => {
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_is_public: e.target.checked,
            };
        });
    };

    const handleSelectCat = (selectedOptions: any) => {
        const coupon_categories = selectedOptions.map((coupon: any) => {
            return coupon.value;
        });
        setCouponForm((prev) => {
            return {
                ...prev,
                coupon_categories: coupon_categories,
            };
        });
    };

    const labelMap: Partial<Record<keyof Coupon, string>> = {
        coupon_name: 'Coupon Code',
        coupon_title: 'Coupon Title',
        coupon_description: 'Description',
        coupon_type: 'Type',
        coupon_amount: 'Amount',
        coupon_is_limited: 'Is Limited',
        coupon_is_individual: 'Is Individual',
        coupon_is_unique_user: 'Is Unique User',
        coupon_is_noticed: 'Is Noticed',
        coupon_is_highlight: 'Is Highlight',
        coupon_notice_desc: 'Notice Desc',
        coupon_start_date: 'Start Date',
        coupon_end_date: 'End Date',
        coupon_limit: 'Usage Limit',
        coupon_min_purchase: 'Min Purchase',
        coupon_max_amount_disc: 'Max Disc Amount',
        coupon_categories: 'Coupon Categories',
        include_product_categories: 'Included Product Categories',
        exclude_product_categories: 'Excluded Product Categories',
        excluded_products: 'Excluded Products',
        included_products: 'Included Products',
        coupon_is_public: 'Is Public',
    };

    const getCouponChangesDescription = () => {
        if (!initialCouponForm) return 'No previous data to compare.';

        const updatedFields: string[] = [];

        (Object.keys(couponForm) as (keyof Coupon)[]).forEach((key) => {
            const oldValue = initialCouponForm[key];
            const newValue = couponForm[key];

            if (Array.isArray(oldValue) && Array.isArray(newValue)) {
                if (oldValue.length !== newValue.length || !oldValue.every((val, index) => val === newValue[index])) {
                    updatedFields.push(`${key}: [Changed: ${oldValue.join(', ')} -> ${newValue.join(', ')}]`);
                }
            } else if (typeof oldValue === 'boolean' || typeof newValue === 'boolean') {
                if (oldValue !== newValue) {
                    updatedFields.push(`${key}: ${oldValue ? 'Yes' : 'No'} -> ${newValue ? 'Yes' : 'No'}`);
                }
            } else if (oldValue instanceof Date && newValue instanceof Date) {
                if (oldValue.getTime() !== newValue.getTime()) {
                    updatedFields.push(`${key}: ${oldValue.toISOString()} -> ${newValue.toISOString()}`);
                }
            } else {
                if (oldValue !== newValue) {
                    const label = labelMap[key] || key;
                    updatedFields.push(`${label}: ${oldValue} -> ${newValue}`);
                }
            }
        });

        return updatedFields.length > 0 ? updatedFields.join(' | ') : 'No changes made.';
    };

    const [isLoading, setIsLoading] = useState(false);

    const isFormEmpty = () => {
        const hasCategories =
            couponForm.coupon_categories.length > 0 ||
            couponForm.include_product_categories.length > 0 ||
            couponForm.exclude_product_categories.length > 0 ||
            couponForm.included_products.length > 0 ||
            couponForm.excluded_products.length > 0;

        return !hasCategories;
    };

    const saveCoupon = async () => {
        if (isFormEmpty()) {
            const result = await Swal.fire({
                title: 'Form Kosong',
                text: 'Include dan exclude categories/products tidak diisi. Tetap ingin menyimpan?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, tetap simpan',
                cancelButtonText: 'Batal',
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
            });

            if (!result.isConfirmed) {
                return;
            }
        }

        setIsLoading(true);

        const couponFormToSave = {
            ...couponForm,
            coupon_name: couponForm.coupon_name.toUpperCase(),
            coupon_title: couponForm.coupon_title,
        } as any;

        const validationSave = SaveCoupon(couponFormToSave);
        if (validationSave.status === false) {
            setIsLoading(false);
            return;
        }
        try {
            const api_url = process.env.API_URL;
            const payload = {
                data: validationSave.data,
            };
            const fetchUrl = isCreate ? `${api_url}api/coupons/store` : `${api_url}api/coupons/${couponForm.id}`;
            const method = isCreate ? 'POST' : 'PUT';
            // login credential
            const response = await fetch(fetchUrl, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });

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

            coloredToast('success', `coupon ${isCreate ? 'created' : 'updated'} successfully`);

            if (isUpdate && initialCouponForm) {
                const changes = getCouponChangesDescription();

                await logActivity({
                    location: 'Coupon Page',
                    description: `Coupon ${couponForm.coupon_name} | Updated: ${changes}`,
                });
            }

            if (isCreate) {
                await logActivity({
                    location: 'Coupon Page',
                    description: `Coupon created: ${couponForm.coupon_name || '[no code]'}`,
                });
            }

            router.push('/coupons');
        } catch (error) {
            console.error(error);
            await logActivity({
                location: 'Coupon Page',
                description: `Coupon gagal di update`,
            });
            coloredToast('danger', 'something went wrong');
        }

        setIsLoading(false);
    };

    return (
        <>
            <div className="panel w-2/3 px-0 py-6 ltr:xl:mr-6 rtl:xl:ml-6">
                <div className="flex gap-8 px-4">
                    <div className="mb-4 w-1/2">
                        {/* <div className="text-lg">Coupon Detail : </div> */}

                        <div className="mt-4 flex items-center">
                            <label htmlFor="coupon_name" className="mb-0 flex-1  ltr:mr-2 rtl:ml-2">
                                Coupon Code
                            </label>
                            <input
                                id="coupon_name"
                                type="text"
                                name="coupon_name"
                                className="form-input w-2/3 uppercase lg:w-[250px]"
                                placeholder="Enter Code"
                                value={couponForm.coupon_name}
                                onChange={handleChange}
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="coupon_title" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Title
                            </label>
                            <textarea
                                id="coupon_title"
                                name="coupon_title"
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="Enter Title"
                                value={couponForm.coupon_title}
                                onChange={handleChange}
                            ></textarea>
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="coupon_description" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Description
                            </label>
                            <textarea
                                id="coupon_description"
                                name="coupon_description"
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="Enter description"
                                value={couponForm.coupon_description}
                                onChange={handleChange}
                            ></textarea>
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="coupon_type" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Coupon Type
                            </label>
                            <select id="coupon_type" name="coupon_type" className="form-select w-2/3 lg:w-[250px]" value={couponForm.coupon_type} onChange={handleChange}>
                                <option value="fixed">Fixed</option>
                                <option value="percentage">Percentage</option>
                                <option value="free_item">Free Item</option>
                            </select>
                        </div>
                        {couponForm.coupon_type === 'free_item' ? (
                            <div className="mt-4 flex items-start">
                                <label className="mb-0 flex-1 pt-2 ltr:mr-2 rtl:ml-2">
                                    Free Item Products
                                </label>
                                <div className="w-2/3 lg:w-[250px]">
                                    <FreeItemProductSelector
                                        productId={couponForm.coupon_free_item_products || []}
                                        isUpdate={isUpdate || (couponForm.coupon_free_item_products || []).length > 0}
                                        onProductChange={async (productIds) => {
                                            let firstTitle = '';
                                            if (productIds.length > 0) {
                                                try {
                                                    const api_url = process.env.API_URL;
                                                    const response = await fetch(`${api_url}api/products/product-list`, {
                                                        method: 'POST',
                                                        headers: { 'Content-Type': 'application/json' },
                                                        body: JSON.stringify({ products: [productIds[0]] }),
                                                        credentials: 'include',
                                                    });
                                                    if (response.ok) {
                                                        const products = await response.json();
                                                        firstTitle = Array.isArray(products) && products[0]
                                                            ? products[0].product_title || ''
                                                            : '';
                                                    }
                                                } catch (e) {
                                                    console.error('Failed to resolve free item title', e);
                                                }
                                            }
                                            setCouponForm((prev) => ({
                                                ...prev,
                                                coupon_free_item_products: productIds,
                                                coupon_free_item_name: firstTitle,
                                            }));
                                        }}
                                    />
                                    <p className="mt-1 text-xs text-white-dark">
                                        Pool produk. Checkout auto-assign 1 item (produk/varian pertama yang stok tersedia).
                                    </p>
                                </div>
                            </div>
                        ) : (
                            <div className="mt-4 flex items-center">
                                <label htmlFor="coupon_amount" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Coupon {couponForm.coupon_type === 'percentage' ? 'Discount' : 'Amount'}
                                </label>
                                <NumberFormatter
                                    name="coupon_amount"
                                    placeholder={couponForm.coupon_type === 'percentage' ? 'Enter percentage discount' : 'Enter fixed amount'}
                                    max={couponForm.coupon_type === 'percentage' ? 3 : undefined}
                                    className="form-input w-2/3 lg:w-[250px]"
                                    value={couponForm.coupon_amount}
                                    onChange={(value) => setCouponForm({ ...couponForm, coupon_amount: value })}
                                />
                            </div>
                        )}

                        {couponForm.coupon_type === 'percentage' && (
                            <div className="mt-4 flex items-center">
                                <label htmlFor="coupon_is_max_disc" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Is Max Discount Amount ?
                                </label>
                                <label className="relative h-6 w-12">
                                    <input
                                        type="checkbox"
                                        onChange={changeIsMaxDisc}
                                        checked={couponForm.coupon_is_max_disc}
                                        className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                        id="coupon_is_max_disc"
                                    />
                                    <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>
                        )}
                        {couponForm.coupon_type === 'percentage' && couponForm.coupon_is_max_disc && (
                            <div className="mt-4 flex items-center">
                                <label htmlFor="coupon_max_amount_disc" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Max disc amount
                                </label>
                                <NumberFormatter
                                    name="coupon_max_amount_disc"
                                    placeholder="Enter minimum purchase"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    value={couponForm.coupon_max_amount_disc}
                                    onChange={(value: any) => setCouponForm({ ...couponForm, coupon_max_amount_disc: value })}
                                />
                            </div>
                        )}
                        <div className="mt-4 flex items-center">
                            <label htmlFor="coupon_min_purchase" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Min Purchase
                            </label>
                            <NumberFormatter
                                name="coupon_min_purchase"
                                placeholder="Enter minimum purchase"
                                className="form-input w-2/3 lg:w-[250px]"
                                value={couponForm.coupon_min_purchase}
                                onChange={(value) => setCouponForm({ ...couponForm, coupon_min_purchase: value })}
                            />
                        </div>
                        <div className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_unique_user" className="mb-0 w-[220px]">
                                    Is Unique User ? (Member Only)
                                </label>
                                <Tooltip title="Kupon hanya untuk user registered saja" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsUniqueUser}
                                    checked={couponForm.coupon_is_unique_user}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_unique_user"
                                />
                                <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 className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_individual" className="mb-0 w-[220px]">
                                    Is Individual ?
                                </label>
                                <Tooltip title="Kupon dapat digabung dengan kupon aktif lainnya" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsIndividual}
                                    checked={couponForm.coupon_is_individual}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_individual"
                                />
                                <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 className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_limited" className="mb-0 w-[220px]">
                                    Is Limited ?
                                </label>
                                <Tooltip title="Pemakaian kupon dibatasi untuk (N) kali pakai" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsLimit}
                                    checked={couponForm.coupon_is_limited}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_limited"
                                />
                                <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>
                        {couponForm.coupon_is_limited && (
                            <div className="mt-4 flex items-center">
                                <label htmlFor="coupon_limit" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Usage Limit
                                </label>
                                <input
                                    id="coupon_limit"
                                    type="number"
                                    name="coupon_limit"
                                    placeholder="Enter coupon limit"
                                    className="form-input w-2/3 lg:w-[250px] mr-4"
                                    value={couponForm.coupon_limit}
                                    onChange={handleChange}
                                />
                                <Tooltip title="Masukan jumlah batas pemakaian kupon" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            
                        )}
                        <div className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_public" className="mb-0 w-[220px]">
                                    Is Public ?
                                </label>
                                <Tooltip title="Kupon ditampilkan di halaman Cart" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsPublic}
                                    checked={couponForm.coupon_is_public}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_public"
                                />
                                <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 className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_highlight" className="mb-0 w-[220px]">
                                    Highlight Coupon ?
                                </label>
                                <Tooltip title="Kupon akan ditampilkan di halaman Cart dengan warna berbeda (lihat preview)" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsHighlight}
                                    checked={couponForm.coupon_is_highlight || false}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_highlight"
                                />
                                <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 className="mt-4 flex items-center justify-between">
                            <div className="flex items-center justify-between w-[280px] gap-2">
                                <label htmlFor="coupon_is_noticed" className="mb-0 w-[220px]">
                                    Notice Coupon ?
                                </label>
                                <Tooltip title="Informasi Kupon seperti nama, kode, syarat, waktu awal dan akhir kupon akan ditampilkan di store notice running text" placement="right-start" style={{ fontSize: '16px' }}><InfoIcon className="text-gray-400" /></Tooltip>
                            </div>
                            <label className="relative h-6 w-12">
                                <input
                                    type="checkbox"
                                    onChange={changeIsNoticed}
                                    checked={couponForm.coupon_is_noticed}
                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                    id="coupon_is_noticed"
                                />
                                <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>
                        {couponForm.coupon_is_noticed && (
                            <div className="mt-4 flex items-center">
                                <label htmlFor="coupon_notice_desc" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                    Store Notice
                                </label>
                                <textarea
                                    id="coupon_notice_desc"
                                    name="coupon_notice_desc"
                                    className="form-input w-2/3 lg:w-[250px]"
                                    placeholder="Max. 25 Characters"
                                    value={couponForm.coupon_notice_desc}
                                    onChange={(e) => {
                                        if (e.target.value.length <= 25) {
                                            handleChange(e);
                                        }
                                    }}
                                    maxLength={25}
                                ></textarea>
                            </div>
                        )}
                    </div>
                    <div className="mb-4 w-1/2">
                        <ProductCategorySelector
                            includeCategories={couponForm.include_product_categories || []}
                            excludeCategories={couponForm.exclude_product_categories || []}
                            includedProducts={couponForm.included_products || []}
                            excludedProducts={couponForm.excluded_products || []}
                            onIncludeCategoriesChange={(categories) => {
                                setCouponForm((prev: any) => ({
                                    ...prev,
                                    include_product_categories: categories,
                                }));
                            }}
                            onExcludeCategoriesChange={(categories) => {
                                setCouponForm((prev: any) => ({
                                    ...prev,
                                    exclude_product_categories: categories,
                                }));
                            }}
                            onIncludedProductsChange={(products) => {
                                setCouponForm((prev: any) => ({
                                    ...prev,
                                    included_products: products,
                                }));
                            }}
                            onExcludedProductsChange={(products) => {
                                setCouponForm((prev: any) => ({
                                    ...prev,
                                    excluded_products: products,
                                }));
                            }}
                            isUpdate={isUpdate}
                        />
                        <div className="custom-select mt-4 flex items-center justify-around">
                            <label htmlFor="coupon_categories" className="mb-0 w-[150px]">
                                Coupon Categories
                            </label>
                            <Select
                                placeholder="Select an option"
                                options={couponCategories}
                                value={couponForm.coupon_categories.map((category) => ({
                                    value: category,
                                    label: category,
                                }))}
                                onChange={handleSelectCat}
                                className="w-2/3 lg:w-[250px]"
                                isMulti
                                isSearchable={true}
                                classNamePrefix="user-form-select"
                            />
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <div className="mt-6 w-full  xl:mt-0 xl:w-full">
                    <div className="panel mb-5">
                        <div className="text-lg">Cart Preview</div>
                        <div className="mt-4">
                            <CouponVoucherPreview couponForm={couponForm} />
                        </div>
                    </div>
                    <div className="panel  mb-5">
                        <div className="text-lg">Schedule Coupon : </div>

                        <div className="mt-4 flex items-center">
                            <label htmlFor="startDate" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                Start Date
                            </label>
                            <Flatpickr
                                data-enable-time
                                options={{
                                    enableTime: true,
                                    dateFormat: 'Y-m-d H:i',
                                    position: 'auto left',
                                    time_24hr: true,
                                }}
                                value={couponForm.coupon_start_date || undefined}
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="yyyy-mm-dd hh:mm"
                                onChange={(dates) =>
                                    setStartDate(Array.isArray(dates) && dates[0] ? dates[0] : null)
                                }
                            />
                        </div>
                        <div className="mt-4 flex items-center">
                            <label htmlFor="endDate" className="mb-0 flex-1 ltr:mr-2 rtl:ml-2">
                                End / Exp Date
                            </label>
                            <Flatpickr
                                data-enable-time
                                options={{
                                    enableTime: true,
                                    dateFormat: 'Y-m-d H:i',
                                    position: 'auto left',
                                    time_24hr: true,
                                }}
                                value={couponForm.coupon_end_date || undefined}
                                className="form-input w-2/3 lg:w-[250px]"
                                placeholder="yyyy-mm-dd hh:mm"
                                onChange={(dates) =>
                                    setEndDate(Array.isArray(dates) && dates[0] ? dates[0] : null)
                                }
                            />
                        </div>
                    </div>
                </div>
                <div className="mt-6 w-full xl:mt-0 xl:w-96">
                    <div className="panel">
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                            <button type="button" disabled={isLoading} onClick={saveCoupon} className="btn btn-success w-full gap-2">
                                {isLoading ? (
                                    <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                ) : (
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 shrink-0 ltr:mr-2 rtl:ml-2">
                                        <path
                                            d="M3.46447 20.5355C4.92893 22 7.28595 22 12 22C16.714 22 19.0711 22 20.5355 20.5355C22 19.0711 22 16.714 22 12C22 11.6585 22 11.4878 21.9848 11.3142C21.9142 10.5049 21.586 9.71257 21.0637 9.09034C20.9516 8.95687 20.828 8.83317 20.5806 8.58578L15.4142 3.41944C15.1668 3.17206 15.0431 3.04835 14.9097 2.93631C14.2874 2.414 13.4951 2.08581 12.6858 2.01515C12.5122 2 12.3415 2 12 2C7.28595 2 4.92893 2 3.46447 3.46447C2 4.92893 2 7.28595 2 12C2 16.714 2 19.0711 3.46447 20.5355Z"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                        />
                                        <path
                                            d="M17 22V21C17 19.1144 17 18.1716 16.4142 17.5858C15.8284 17 14.8856 17 13 17H11C9.11438 17 8.17157 17 7.58579 17.5858C7 18.1716 7 19.1144 7 21V22"
                                            stroke="currentColor"
                                            strokeWidth="1.5"
                                        />
                                        <path opacity="0.5" d="M7 8H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                    </svg>
                                )}
                                Save
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};
export default CouponForm;
