import { useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import 'mantine-datatable/styles.css';
import { DataTable, type DataTableSortStatus } from '@/components/Shared/DataTable';

import { setPageTitle } from '../../store/themeConfigSlice';
import Link from 'next/link';
import FilterCoupon from '@/components/Coupons/FilterCoupons';
import Tippy from '@tippyjs/react';
import 'tippy.js/dist/tippy.css';
import { coloredToast, progressToast, deleteToast, confirmToast } from '@/lib/toast';
interface Coupon {
    id: string;
    coupon_name: string;
    coupon_amount: number;
    coupon_type: string;
    coupon_used: number;
    coupon_limit: number;
    coupon_free_item_name: string;
    coupon_free_item_products?: string[];
    coupon_start_date: Date;
    coupon_end_date: Date;
    coupon_categories: [];
    createdAt: Date;
    coupon_is_highlight?: boolean;
    coupon_is_public?: boolean;
}
interface Filter {
    coupon_type: string;
    coupon_categories: string;
}
const CouponIndex = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Coupon'));
    }, []);
    const [isMounted, setIsMounted] = useState(false);

    useEffect(() => {
        setIsMounted(true);
    }, []);

    const [isLoading, setIsLoading] = useState(true); // Add isLoading state
    const [showModalFilter, setShowModalFilter] = useState(false);
    const [showMemberNoticeModal, setShowMemberNoticeModal] = useState(false);

    const [appliedFilter, setAppliedFilter] = useState<Filter>({
        coupon_type: '',
        coupon_categories: '',
    });

    const [isFiltered, setIsFiltered] = useState(false);

    const [page, setPage] = useState(1);
    const PAGE_SIZES = [5, 10, 20, 30, 50, 100];
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [records, setRecords] = useState<Coupon[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [bulkData, setBulkData] = useState<any>([]);
    const [isBulkButton, setIsBulkButton] = useState(false);
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus<any>>({ columnAccessor: 'status', direction: 'asc' });
    const [memberNotice, setMemberNotice] = useState<{ for_login?: string; not_login?: string }>({});

    const highlightedCoupon = useMemo(
        () => records.find((coupon) => coupon.coupon_is_highlight) || null,
        [records]
    );

    const publicCoupon = useMemo(
        () => records.find((coupon) => coupon.coupon_is_public) || null,
        [records]
    );

    const handleSortStatusChange = (newSortStatus: DataTableSortStatus<any>) => {
        setSortStatus(newSortStatus);
        if (newSortStatus.columnAccessor && newSortStatus.columnAccessor !== sortStatus.columnAccessor && page !== 1) {
            setPage(1);
        }
    };

    // Fetch data from API
    const fetchData = async () => {
        setIsLoading(true);
        try {
            let filter = '';

            if (appliedFilter.coupon_categories) {
                filter += `&coupon_categories=${appliedFilter.coupon_categories}`;
            }

            if (appliedFilter.coupon_type) {
                filter += `&coupon_type=${appliedFilter.coupon_type}`;
            }

            let sortParam = '';
            if (sortStatus && sortStatus.columnAccessor) {
                sortParam = `&sort_by=${String(sortStatus.columnAccessor)}&sort_direction=${sortStatus.direction}`;
            }

            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/coupons/list?page=${page}&per_page=${pageSize}&q=${search}&${filter}${sortParam}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });

            const member_notice_response = await fetch(`${api_url}api/setting/member-notice`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            const data = await response.json();
            const member_notice_data = await member_notice_response.json();

            setMemberNotice(member_notice_data);
            setPage(data.currentPage);
            setTotalRecords(data.totalData);
            setRecords(Array.isArray(data.data) ? data.data : []);

            setIsLoading(false);
        } catch (error) {
            console.error('Error fetching data:', error);
            setIsLoading(false);
        }
    };

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

    const applyFilter = () => {
        setIsFiltered(true);
        setShowModalFilter(false);
        if (page !== 1) {
            setPage(1);
        } else {
            fetchData();
        }
    };

    const removeFilter = () => {
        setAppliedFilter({
            ...appliedFilter,
            coupon_type: '',
            coupon_categories: '',
        });
        setIsFiltered(false);
    };

    const handleKeypress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.keyCode === 13) {
            if (page !== 1) {
                setPage(1);
            } else {
                fetchData();
            }
        }
    };

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

    const handleDelete = async (id: string) => {
        const result = await deleteToast('Are you sure want to delete this coupon?');
        if (result) {
            try {
                const api_url = process.env.API_URL;
                const response = await fetch(`${api_url}api/coupons/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'include',
                });
                if (!response.ok) {
                    throw new Error(`Failed to delete coupon with id ${id}`);
                } else {
                    fetchData();
                    coloredToast('success', 'Expired coupon has been deleted');
                }
            } catch (error) {
                console.error('Error deleting expired coupons:', error);
            }
        }
    };

    const handleClone = async (id: string) => {
        const result = await confirmToast('Are you sure want to clone this coupon?', 'clone');
        if (result) {
            try {
                const api_url = process.env.API_URL;
                const response = await fetch(`${api_url}api/coupons/clone/${id}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'include',
                });

                if (!response.ok) {
                    throw new Error(`Failed to clone coupon with id ${id}`);
                } else {
                    fetchData();
                    coloredToast('success', 'Coupon has been cloned successfully');
                }
            } catch (error) {
                console.error('Error cloning coupon:', error);
                coloredToast('error', 'Failed to clone coupon');
            }
        }
    };

    const handleToggleHighlight = async (id: string, highlight: boolean) => {
        if (
            highlight &&
            highlightedCoupon &&
            highlightedCoupon.id !== id
        ) {
            coloredToast(
                'warning',
                `Coupon '${highlightedCoupon.coupon_name}' is already highlighted. Turn it off first.`
            );
            return;
        }

        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/coupons/${id}/highlight`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
                body: JSON.stringify({ coupon_is_highlight: highlight }),
            });

            const data = await response.json().catch(() => ({}));

            if (!response.ok) {
                coloredToast('warning', data.message || 'Failed to update highlight');
                return;
            }

            fetchData();
            coloredToast('success', highlight ? 'Coupon highlighted' : 'Highlight removed');
        } catch (error) {
            console.error('Error updating coupon highlight:', error);
            coloredToast('error', 'Failed to update highlight');
        }
    };

    const handleDeleteExpiredCoupon = async (id: any, delayMs: number) => {
        const result = await deleteToast('Are you sure want to bulk delete expired coupon?');
        if (result) {
            try {
                const api_url = process.env.API_URL;
                let count = 0;

                progressToast(`Deleting Data`, count, bulkData.length);

                for (const data of bulkData) {
                    await delay(delayMs);
                    const response = await fetch(`${api_url}api/coupons/${data.id}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        credentials: 'include',
                    });
                    if (!response.ok) {
                        coloredToast('warning', `Some Data is not deleted`);
                    } else {
                        count++;
                        progressToast(`Deleting Coupons `, count, bulkData.length);
                    }
                }
                fetchData();
                setBulkData([]);
                setIsBulkButton(false);
                coloredToast('success', 'Selected Coupons has been deleted');
            } catch (error) {
                console.error('Error deleting expired coupons:', error);
            }
        }
    };

    const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

    const getStatus = (item: Coupon) => {
        const currentDate = new Date();
        let status = 'running';

        if (item.coupon_end_date) {
            const endDate = new Date(item.coupon_end_date);
            if (endDate < currentDate) {
                status = 'expired';
            }
        }

        if (item.coupon_start_date) {
            const startDate = new Date(item.coupon_start_date);
            if (startDate > currentDate) {
                status = 'scheduled';
            }
        }

        return status;
    };

    const handleUpdateMemberNotice = async () => {
        try {
            const data = {
                member_notice: {
                    for_login: memberNotice.for_login || '',
                    not_login: memberNotice.not_login || '',
                },
            };

            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/setting/member-notice`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
                credentials: 'include',
            });

            if (!response.ok) {
                throw new Error('Failed to update member notice');
            }
            coloredToast('success', 'Member notice has been updated');
            setShowMemberNoticeModal(false);
        } catch (error) {
            console.error('Error updating member notice:', error);
        }
    };

    return (
        <>
            {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <span>Coupons</span>
                                </li>
                            </ul>
                        </div>
                        <FilterCoupon
                            showModalFilter={showModalFilter}
                            setShowModalFilter={setShowModalFilter}
                            appliedFilter={appliedFilter}
                            setAppliedFilter={setAppliedFilter}
                            applyFilter={applyFilter}
                        />
                        <div className="panel border-white-light dark:border-[#1b2e4b]">
                            <div className="invoice-table">
                                <div className="mb-4.5 flex flex-col gap-5 px-5 md:flex-row md:items-center">
                                    <div className="flex items-center gap-2">
                                        <div>
                                            <Link href="/coupons/add" className="btn btn-outline-primary gap-2">
                                                <svg className="h-5 w-5" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round">
                                                    <line x1="12" y1="5" x2="12" y2="19"></line>
                                                    <line x1="5" y1="12" x2="19" y2="12"></line>
                                                </svg>
                                                Add New Coupon
                                            </Link>
                                        </div>
                                        <Link href="/coupons/categories" className="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
                                                    opacity="0.5"
                                                    d="M2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2C16.714 2 19.0711 2 20.5355 3.46447C22 4.92893 22 7.28595 22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12Z"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                />
                                                <path d="M6 15.8L7.14286 17L10 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                <path d="M6 8.8L7.14286 10L10 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                <path d="M13 9L18 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                <path d="M13 16L18 16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                            </svg>
                                            List Categories
                                        </Link>
                                        {isBulkButton ? (
                                            <div>
                                                <button onClick={() => handleDeleteExpiredCoupon(bulkData, 800)} className="btn btn-outline-danger gap-2">
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none">
                                                        <path d="M10 12V17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                        <path d="M14 12V17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                        <path d="M4 7H20" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                        <path
                                                            d="M6 10V18C6 19.6569 7.34315 21 9 21H15C16.6569 21 18 19.6569 18 18V10"
                                                            stroke="currentColor"
                                                            strokeWidth="2"
                                                            strokeLinecap="round"
                                                            strokeLinejoin="round"
                                                        />
                                                        <path
                                                            d="M9 5C9 3.89543 9.89543 3 11 3H13C14.1046 3 15 3.89543 15 5V7H9V5Z"
                                                            stroke="currentColor"
                                                            strokeWidth="2"
                                                            strokeLinecap="round"
                                                            strokeLinejoin="round"
                                                        />
                                                    </svg>
                                                    Delete {`${bulkData.length}`} Expired Coupon
                                                </button>
                                            </div>
                                        ) : null}
                                        <div></div>
                                    </div>
                                    <div className="flex ltr:ml-auto rtl:mr-auto">
                                        <div className="mr-2 flex items-center">
                                            <Tippy content="Filter">
                                                <button type="button" className={`flex items-center hover:text-primary ${isFiltered ? 'text-primary' : ''}`} onClick={() => setShowModalFilter(true)}>
                                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                                        <path
                                                            opacity="0.5"
                                                            d="M2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2C16.714 2 19.0711 2 20.5355 3.46447C22 4.92893 22 7.28595 22 12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12Z"
                                                            stroke="currentColor"
                                                            strokeWidth="1.5"
                                                        />
                                                        <path
                                                            d="M10 14C11.1046 14 12 14.8954 12 16C12 17.1046 11.1046 18 10 18C8.89543 18 8 17.1046 8 16C8 14.8954 8.89543 14 10 14Z"
                                                            stroke="currentColor"
                                                            strokeWidth="1.5"
                                                        />
                                                        <circle cx="2" cy="2" r="2" transform="matrix(-4.37114e-08 -1 -1 4.37114e-08 16 10)" stroke="currentColor" strokeWidth="1.5" />
                                                        <path d="M14 16L19 16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                        <path d="M10 8L5 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                        <path d="M5 16L6 16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                        <path d="M19 8L18 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    </svg>
                                                </button>
                                            </Tippy>
                                            {isFiltered && (
                                                <div className="badge badge-outline-danger ms-2 cursor-pointer " onClick={() => removeFilter()}>
                                                    <span className="flex items-center">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                                            <path d="M14.5 9.50002L9.5 14.5M9.49998 9.5L14.5 14.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                        </svg>
                                                        Remove Filter
                                                    </span>
                                                </div>
                                            )}
                                        </div>
                                        <input
                                            type="text"
                                            className="form-input w-auto"
                                            placeholder="Search Coupon Name"
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            onKeyDown={handleKeypress}
                                        />
                                    </div>
                                </div>
                                <div className="mb-4.5 flex flex-col gap-2 px-5 md:flex-row md:items-center">
                                    <div className="w-full">
                                        <button className="btn btn-outline-primary gap-2" onClick={() => setShowMemberNoticeModal(true)}>
                                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none">
                                                <path
                                                    d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                />
                                                <path d="M12 8V13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                <path d="M11.9945 16H12.0035" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                                            </svg>
                                            Member Notice
                                        </button>
                                    </div>
                                </div>
                                <div className="datatables pagination-padding">
                                    {isLoading ? (
                                        // Show loading indicator here
                                        <div className="flex justify-center py-4 text-center">
                                            <svg
                                                viewBox="0 0 24 24"
                                                width="24"
                                                height="24"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                fill="none"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                className="h-5 w-5 animate-spin text-white-dark"
                                            >
                                                <line x1="12" y1="2" x2="12" y2="6"></line>
                                                <line x1="12" y1="18" x2="12" y2="22"></line>
                                                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                <line x1="2" y1="12" x2="6" y2="12"></line>
                                                <line x1="18" y1="12" x2="22" y2="12"></line>
                                                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                            </svg>
                                            <span className="ms-3">Please wait, we&apos;re still working to load the data...</span>
                                        </div>
                                    ) : (
                                        <DataTable
                                            className="table-hover whitespace-nowrap"
                                            records={records}
                                            minHeight={250}
                                            withTableBorder
                                            selectedRecords={bulkData}
                                            onSelectedRecordsChange={(selectedRecords) => {
                                                setBulkData(selectedRecords);
                                                setIsBulkButton(selectedRecords.length > 0);
                                            }}
                                            isRecordSelectable={(record) => {
                                                if (!record.coupon_end_date) return false;
                                                const currentDate = new Date();
                                                const endDate = new Date(record.coupon_end_date);
                                                return currentDate > endDate;
                                            }}
                                            noRecordsText="No data found"
                                            sortStatus={sortStatus}
                                            onSortStatusChange={handleSortStatusChange}
                                            columns={[
                                                {
                                                    accessor: 'coupon_name',
                                                    sortable: true,
                                                    render: ({ id, coupon_name }) => {
                                                        const isClone = coupon_name.includes(' - clone');
                                                        const displayName = isClone ? coupon_name.replace(' - clone', '') : coupon_name;

                                                        return (
                                                            <Link href={`/coupons/edit/${id}`}>
                                                                <div className="text-xs font-semibold hover:no-underline">
                                                                    {displayName}
                                                                    {isClone && <span className="ml-1 text-green-500">- clone</span>}
                                                                </div>
                                                            </Link>
                                                        );
                                                    },
                                                },

                                                {
                                                    accessor: 'type',
                                                    render: ({ coupon_type }) => <>{coupon_type}</>,
                                                },
                                                {
                                                    accessor: 'amount',
                                                    render: ({ coupon_type, coupon_amount, coupon_free_item_name, coupon_free_item_products }) => (
                                                        <>
                                                            {coupon_type === 'percentage'
                                                                ? coupon_amount + '%'
                                                                : coupon_type === 'fixed'
                                                                ? 'Rp ' + coupon_amount.toLocaleString('id-ID')
                                                                : 'Free ' +
                                                                  (coupon_free_item_name ||
                                                                      (Array.isArray(coupon_free_item_products) &&
                                                                      coupon_free_item_products.length
                                                                          ? `${coupon_free_item_products.length} product(s)`
                                                                          : 'item'))}
                                                        </>
                                                    ),
                                                },
                                                {
                                                    accessor: 'created date',
                                                    render: ({ createdAt }) => {
                                                        const createdAtDate = new Date(createdAt);
                                                        const formattedDate = createdAtDate.toLocaleDateString('id-ID'); // Format the date
                                                        const formattedTime = createdAtDate.toLocaleTimeString('id-ID'); // Format the time
                                                        return (
                                                            <>
                                                                <div className="text-xs">
                                                                    <div>{formattedDate}</div>
                                                                    <div>{formattedTime}</div>
                                                                </div>
                                                            </>
                                                        ); // Render the formatted date and time
                                                    },
                                                },
                                                {
                                                    accessor: 'usage / limit',
                                                    render: ({ coupon_used, coupon_limit }) => {
                                                        return (
                                                            <>
                                                                {coupon_used} / {coupon_limit === 0 ? '\u221E' : coupon_limit}
                                                            </>
                                                        );
                                                    },
                                                },
                                                {
                                                    accessor: 'categories',
                                                    render: ({ coupon_categories }) => {
                                                        return coupon_categories.map((coupon: string, index: number) => {
                                                            return <div key={index}>{coupon}</div>;
                                                        });
                                                    },
                                                },
                                                {
                                                    accessor: 'status',
                                                    sortable: true,
                                                    render: ({ coupon_start_date, coupon_end_date }) => {
                                                        const status = getStatus({ coupon_start_date, coupon_end_date } as Coupon);

                                                        // Define CSS classes based on the status
                                                        let statusClass = 'badge badge-outline-success w-fit';
                                                        if (status === 'expired') {
                                                            statusClass = 'badge badge-outline-danger  w-fit';
                                                        } else if (status === 'scheduled') {
                                                            statusClass = 'badge badge-outline-warning w-fit';
                                                        }

                                                        // Return the status element with the appropriate styling
                                                        return <div className={statusClass}>{status}</div>;
                                                    },
                                                },
                                                {
                                                    accessor: 'coupon_is_highlight',
                                                    title: 'Highlight',
                                                    sortable: true,
                                                    textAlign: 'center',
                                                    render: ({ id, coupon_is_highlight }) => {
                                                        const isBlocked =
                                                            !coupon_is_highlight &&
                                                            Boolean(
                                                                highlightedCoupon &&
                                                                    highlightedCoupon.id !== id
                                                            );
                                                        const tippyContent = coupon_is_highlight
                                                            ? 'Remove highlight'
                                                            : isBlocked
                                                              ? `Turn off highlight on '${highlightedCoupon?.coupon_name}' first`
                                                              : 'Highlight coupon';

                                                        return (
                                                        <div className="flex justify-center">
                                                            <Tippy content={tippyContent}>
                                                                <button
                                                                    type="button"
                                                                    onClick={() =>
                                                                        handleToggleHighlight(
                                                                            id,
                                                                            !coupon_is_highlight
                                                                        )
                                                                    }
                                                                    disabled={isBlocked}
                                                                    className={`flex ${
                                                                        coupon_is_highlight
                                                                            ? 'text-warning'
                                                                            : isBlocked
                                                                              ? 'cursor-not-allowed opacity-40 text-gray-400'
                                                                              : 'text-gray-600 hover:text-warning dark:text-white'
                                                                    }`}
                                                                >
                                                                    <svg
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        width="20"
                                                                        height="20"
                                                                        viewBox="0 0 24 24"
                                                                        fill={
                                                                            coupon_is_highlight
                                                                                ? 'currentColor'
                                                                                : 'none'
                                                                        }
                                                                    >
                                                                        <path
                                                                            d="M12 2l2.9 6.26L22 9.27l-5 4.87L18.2 22 12 18.56 5.8 22 7 14.14l-5-4.87 7.1-1.01L12 2z"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                            strokeLinejoin="round"
                                                                        />
                                                                    </svg>
                                                                </button>
                                                            </Tippy>
                                                        </div>
                                                        );
                                                    },
                                                },
                                                {
                                                    accessor: 'action',
                                                    title: 'Actions',
                                                    textAlign: 'center',
                                                    render: ({ id }) => (
                                                        <div className="mx-auto flex w-max items-center gap-4">
                                                            <Tippy content="Clone">
                                                                <button onClick={() => handleClone(id)} className="flex hover:text-success">
                                                                    <svg
                                                                        className="h-6 w-6 text-gray-600 dark:text-white"
                                                                        aria-hidden="true"
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        width="24"
                                                                        height="24"
                                                                        fill="none"
                                                                        viewBox="0 0 24 24"
                                                                    >
                                                                        <path
                                                                            stroke="currentColor"
                                                                            strokeLinejoin="round"
                                                                            strokeWidth="1.2"
                                                                            d="M15 4v3a1 1 0 0 1-1 1h-3m2 10v1a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-7.13a1 1 0 0 1 .24-.65L6.7 8.35A1 1 0 0 1 7.46 8H9m-1 4H4m16-7v10a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V7.87a1 1 0 0 1 .24-.65l2.46-2.87a1 1 0 0 1 .76-.35H19a1 1 0 0 1 1 1Z"
                                                                        />
                                                                    </svg>
                                                                </button>
                                                            </Tippy>
                                                            <Tippy content="Edit">
                                                                <Link href={`/coupons/edit/${id}`} className="flex hover:text-info">
                                                                    <svg
                                                                        width="24"
                                                                        height="24"
                                                                        viewBox="0 0 24 24"
                                                                        fill="none"
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        className="h-4.5 w-4.5 text-gray-600 dark:text-white"
                                                                    >
                                                                        <path
                                                                            opacity="0.5"
                                                                            d="M22 10.5V12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2H13.5"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                            strokeLinecap="round"
                                                                        ></path>
                                                                        <path
                                                                            d="M17.3009 2.80624L16.652 3.45506L10.6872 9.41993C10.2832 9.82394 10.0812 10.0259 9.90743 10.2487C9.70249 10.5114 9.52679 10.7957 9.38344 11.0965C9.26191 11.3515 9.17157 11.6225 8.99089 12.1646L8.41242 13.9L8.03811 15.0229C7.9492 15.2897 8.01862 15.5837 8.21744 15.7826C8.41626 15.9814 8.71035 16.0508 8.97709 15.9619L10.1 15.5876L11.8354 15.0091C12.3775 14.8284 12.6485 14.7381 12.9035 14.6166C13.2043 14.4732 13.4886 14.2975 13.7513 14.0926C13.9741 13.9188 14.1761 13.7168 14.5801 13.3128L20.5449 7.34795L21.1938 6.69914C22.2687 5.62415 22.2687 3.88124 21.1938 2.80624C20.1188 1.73125 18.3759 1.73125 17.3009 2.80624Z"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                        ></path>
                                                                        <path
                                                                            opacity="0.5"
                                                                            d="M16.6522 3.45508C16.6522 3.45508 16.7333 4.83381 17.9499 6.05034C19.1664 7.26687 20.5451 7.34797 20.5451 7.34797M10.1002 15.5876L8.4126 13.9"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                        ></path>
                                                                    </svg>
                                                                </Link>
                                                            </Tippy>

                                                            <Tippy content="Delete">
                                                                <button onClick={() => handleDelete(id)} className="flex hover:text-danger">
                                                                    <svg
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        width="20"
                                                                        height="20"
                                                                        viewBox="0 0 24 24"
                                                                        fill="none"
                                                                        className="text-gray-600 dark:text-white"
                                                                    >
                                                                        <path d="M10 12V17" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                                        <path d="M14 12V17" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                                        <path d="M4 7H20" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                                        <path
                                                                            d="M6 10V18C6 19.6569 7.34315 21 9 21H15C16.6569 21 18 19.6569 18 18V10"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                            strokeLinecap="round"
                                                                            strokeLinejoin="round"
                                                                        />
                                                                        <path
                                                                            d="M9 5C9 3.89543 9.89543 3 11 3H13C14.1046 3 15 3.89543 15 5V7H9V5Z"
                                                                            stroke="currentColor"
                                                                            strokeWidth="1.5"
                                                                            strokeLinecap="round"
                                                                            strokeLinejoin="round"
                                                                        />
                                                                    </svg>
                                                                </button>
                                                            </Tippy>
                                                        </div>
                                                    ),
                                                },
                                            ]}
                                            highlightOnHover
                                            totalRecords={totalRecords}
                                            recordsPerPage={pageSize}
                                            page={page}
                                            onPageChange={(p) => setPage(p)}
                                            recordsPerPageOptions={PAGE_SIZES}
                                            onRecordsPerPageChange={setPageSize}
                                            paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} coupons`}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                    </>
                )}

                {/* Member Notice Modal */}
                {showMemberNoticeModal && (
                    <div className="fixed inset-0 z-[999] grid place-content-center bg-black bg-opacity-60">
                        <div className="h-[430px] w-[430px] rounded-lg bg-white p-0 shadow-lg dark:bg-[#1e293b]">
                            <div className="flex items-center justify-between border-b border-[#e5e7eb] p-5 dark:border-[#3b3f5c]">
                                <h5 className="text-lg font-semibold dark:text-white">Member Notice</h5>
                                <button type="button" className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300" onClick={() => setShowMemberNoticeModal(false)}>
                                    <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
                                        <path
                                            fillRule="evenodd"
                                            d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                            clipRule="evenodd"
                                        ></path>
                                    </svg>
                                </button>
                            </div>
                            <div className="p-5">
                                <div className="mb-4">
                                    <label htmlFor="memberNotice" className="mb-2 block text-sm font-medium text-green-500 dark:text-gray-300">
                                        Member Notice For Login Member
                                    </label>
                                    <textarea
                                        id="memberNoticeLogin"
                                        className="form-textarea w-full"
                                        placeholder="Enter member notice text..."
                                        value={memberNotice.for_login || ''}
                                        onChange={(e) => setMemberNotice({ ...memberNotice, for_login: e.target.value })}
                                        rows={4}
                                    />
                                    <label htmlFor="memberNoticeNotLogin" className="mb-2 block text-sm font-medium text-red-500 dark:text-gray-300">
                                        Member Notice For Not Login Member
                                    </label>
                                    <textarea
                                        id="memberNoticeNotLogin"
                                        className="form-textarea w-full"
                                        placeholder="Enter member notice text..."
                                        value={memberNotice.not_login || ''}
                                        onChange={(e) => setMemberNotice({ ...memberNotice, not_login: e.target.value })}
                                        rows={4}
                                    />
                                </div>
                                <div className="flex justify-end gap-2">
                                    <button type="button" className="btn btn-outline-danger" onClick={() => setShowMemberNoticeModal(false)}>
                                        Cancel
                                    </button>
                                    <button type="button" className="btn btn-primary" onClick={handleUpdateMemberNotice}>
                                        Update Notice
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
        </>
    );
};

export default CouponIndex;
