import { useEffect, Fragment, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import 'mantine-datatable/styles.css';
import { Dialog, Transition } from '@headlessui/react';
import { setPageTitle } from '../../../store/themeConfigSlice';
import Link from 'next/link';
import { coloredToast } from '@/lib/toast';
import { DataTable } from '@/components/Shared/DataTable';

interface Review {
    _id: string;
    category: string;
    total: number;
    user_name: string;
    stars: number;
    review: string;
    product_title: string;
    createdAt: string;
    is_approved: boolean;
}
const ProductReview = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Review'));
    }, []);

    const [updateReview, setUpdateReview] = useState<any>(false);

    const defaultCategory = {
        review: '',
        stars: 0,
        user_name: '',
        _id: '',
    };
    const [review, setReview] = useState(defaultCategory);
    const [isLoading, setIsLoading] = useState(true); // Add isLoading state
    const [isMounted, setIsMounted] = 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<Review[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [stars, setStars] = useState('');

    // Fetch data from API
    const fetchData = async () => {
        setIsLoading(true); // Set isLoading to true before fetching data
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/review/list?page=${page}&per_page=${pageSize}&stars=${stars}&q=${search}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();

            setPage(data.currentPage);
            setTotalRecords(data.totalData);
            setRecords(data.data);

            setIsLoading(false); // Set isLoading to false after data is fetched
        } catch (error) {
            console.error('Error fetching data:', error);
            setIsLoading(false); // Set isLoading to false even if there's an error
        }
    };

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

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

    const editReview = (user_name: string, stars: any, review: string, _id: any) => {
        if (_id) {
            setReview((prev) => {
                return {
                    user_name: user_name,
                    review: review,
                    stars: stars,
                    _id: _id,
                };
            });
        } else {
            setReview(defaultCategory);
        }
        setUpdateReview(true);
    };

    const changeValue = (e: any) => {
        const { name, value } = e.target;
        setReview((prev) => {
            return {
                ...prev,
                [name]: value,
            };
        });
    };
    const saveUpdateReview = async () => {
        try {
            const api_url = process.env.API_URL;
            const _id = review._id;
            const fetchUrl = `${api_url}api/products/review/update/${_id}`;
            const payload = {
                review: review.review,
                stars: review.stars,
            };
            const response = await fetch(fetchUrl, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
                body: JSON.stringify(payload),
            });
            if (!response.ok) {
                const res = await response.json();
                throw new Error(res.message);
            }
            coloredToast('success', `Review update successfully`);
            fetchData();
        } catch (error: any) {
            console.error(error);
            coloredToast('warning', `${error.message || 'something went wrong'}`);
        }
        setUpdateReview(false);
    };

    const changeActive = async (e: any, id: string) => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/review/approve/${id}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    is_approved: e.target.checked,
                }),
                credentials: 'include', // Include this option
            });

            if (!response.ok) {
                coloredToast('warning', 'Something Wrong');
                return;
            }
            coloredToast('success', 'Review Update');
            fetchData();
        } catch (error) {
            console.error('Error fetching data:', error);
            coloredToast('warning', 'Something Wrong');
        }
    };

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

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

    return (
        <>
                {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <Link href="/products" className="text-primary hover:underline">
                                        Product
                                    </Link>
                                </li>
                                <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                                    <span>reviews</span>
                                </li>
                            </ul>
                        </div>
                        <div className="panel border-white-light px-0 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">
                                        {/* <button onClick={() => editCategory()} 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 Category
                                        </button> */}
                                        <select name="" id="1" className="form-select" onChange={(e) => setStars(e.target.value)}>
                                            <option value="" defaultValue={''}>
                                                All Rating
                                            </option>
                                            <option value="1">⭐</option>
                                            <option value="2">⭐⭐</option>
                                            <option value="3">⭐⭐⭐</option>
                                            <option value="4">⭐⭐⭐⭐</option>
                                            <option value="5">⭐⭐⭐⭐⭐</option>
                                        </select>
                                    </div>
                                    <div className="flex ltr:ml-auto rtl:mr-auto">
                                        <input
                                            type="text"
                                            className="form-input w-auto"
                                            placeholder="Search Review"
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            onKeyDown={handleKeypress}
                                        />
                                    </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}
                                            noRecordsText="No data found"
                                            columns={[
                                                {
                                                    accessor: 'user_name',
                                                    render: ({ user_name }) => <>{user_name}</>,
                                                },
                                                {
                                                    accessor: 'rating',
                                                    render: ({ stars }) => (
                                                        <>
                                                            <div className="flex gap-1">
                                                                {[...Array(5)].map((_, index) => (
                                                                    <svg
                                                                        key={`star-${index}`}
                                                                        height="14"
                                                                        width="14"
                                                                        version="1.1"
                                                                        id="Capa_1"
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        viewBox="0 0 47.94 47.94"
                                                                        fill={index < stars ? '#FCD53F' : '#FFFFFF'}
                                                                    >
                                                                        <path
                                                                            d="M26.285,2.486l5.407,10.956c0.376,0.762,1.103,1.29,1.944,1.412l12.091,1.757
                                                                            c2.118,0.308,2.963,2.91,1.431,4.403l-8.749,8.528c-0.608,0.593-0.886,1.448-0.742,2.285l2.065,12.042
                                                                            c0.362,2.109-1.852,3.717-3.746,2.722l-10.814-5.685c-0.752-0.395-1.651-0.395-2.403,0l-10.814,5.685
                                                                            c-1.894,0.996-4.108-0.613-3.746-2.722l2.065-12.042c0.144-0.837-0.134-1.692-0.742-2.285l-8.749-8.528
                                                                            c-1.532-1.494-0.687-4.096,1.431-4.403l12.091-1.757c0.841-0.122,1.568-0.65,1.944-1.412l5.407-10.956
                                                                            C22.602,0.567,25.338,0.567,26.285,2.486z"
                                                                            stroke={index < stars ? '#FCD53F' : 'currentColor'}
                                                                            opacity="1"
                                                                            strokeWidth="1.5"
                                                                            strokeLinecap="round"
                                                                        />
                                                                    </svg>
                                                                ))}
                                                            </div>
                                                        </>
                                                    ),
                                                },

                                                {
                                                    accessor: 'review',
                                                    render: ({ review }) => (
                                                        <>
                                                            <div className="whitespace-normal">{review}</div>
                                                        </>
                                                    ),
                                                },
                                                {
                                                    accessor: 'product_title',
                                                    title: 'Product',
                                                    render: ({ product_title }) => <>{product_title}</>,
                                                },
                                                {
                                                    accessor: 'createdAt',
                                                    title: 'Date',
                                                    render: ({ createdAt }) => <>{new Date(createdAt).toLocaleDateString('id-ID', { year: 'numeric', month: 'short', day: 'numeric' })}</>,
                                                },
                                                {
                                                    accessor: 'is approved',
                                                    textAlign: 'center',
                                                    render: ({ is_approved, _id }) => (
                                                        <>
                                                            <label className="relative mx-auto h-6 w-12">
                                                                <input
                                                                    checked={is_approved}
                                                                    onChange={(e) => changeActive(e, _id)}
                                                                    type="checkbox"
                                                                    className="custom_switch peer absolute z-10 h-full w-full cursor-pointer opacity-0"
                                                                    id="custom_switch_checkbox1"
                                                                />
                                                                <span className="block h-full rounded-full bg-[#ebedf2] before:absolute before:bottom-1 before:left-1 before:h-4 before:w-4 before:rounded-full before:bg-white before:transition-all before:duration-300 peer-checked:bg-primary peer-checked:before:left-7 dark:bg-dark dark:before:bg-white-dark dark:peer-checked:before:bg-white"></span>
                                                            </label>
                                                        </>
                                                    ),
                                                },

                                                {
                                                    accessor: 'action',
                                                    title: 'Actions',
                                                    textAlign: 'center',
                                                    render: ({ user_name, stars, review, _id }) => (
                                                        <div className="mx-auto flex w-max items-center gap-4">
                                                            <button onClick={() => editReview(user_name, stars, review, _id)}>
                                                                <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">
                                                                    <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>
                                                            </button>
                                                        </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} categories`}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>

                        <Transition appear show={updateReview} as={Fragment}>
                            <Dialog as="div" open={updateReview} onClose={() => setUpdateReview(false)} className="relative z-50">
                                <Transition.Child
                                    as={Fragment}
                                    enter="ease-out duration-300"
                                    enterFrom="opacity-0"
                                    enterTo="opacity-100"
                                    leave="ease-in duration-200"
                                    leaveFrom="opacity-100"
                                    leaveTo="opacity-0"
                                >
                                    <div className="fixed inset-0 bg-[black]/60" />
                                </Transition.Child>
                                <div className="fixed inset-0 overflow-y-auto">
                                    <div className="flex min-h-full items-center justify-center px-4 py-8">
                                        <Transition.Child
                                            as={Fragment}
                                            enter="ease-out duration-300"
                                            enterFrom="opacity-0 scale-95"
                                            enterTo="opacity-100 scale-100"
                                            leave="ease-in duration-200"
                                            leaveFrom="opacity-100 scale-100"
                                            leaveTo="opacity-0 scale-95"
                                        >
                                            <Dialog.Panel className="panel w-full max-w-lg overflow-hidden rounded-lg border-0 p-0 text-black dark:text-white-dark">
                                                <button
                                                    type="button"
                                                    onClick={() => setUpdateReview(false)}
                                                    className="absolute top-4 text-gray-400 outline-none hover:text-gray-800 dark:hover:text-gray-600 ltr:right-4 rtl:left-4"
                                                >
                                                    <svg
                                                        xmlns="http://www.w3.org/2000/svg"
                                                        width="24"
                                                        height="24"
                                                        viewBox="0 0 24 24"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                    >
                                                        <line x1="18" y1="6" x2="6" y2="18"></line>
                                                        <line x1="6" y1="6" x2="18" y2="18"></line>
                                                    </svg>
                                                </button>
                                                <div className="bg-[#fbfbfb] py-3 text-lg font-medium dark:bg-[#121c2c] ltr:pl-5 ltr:pr-[50px] rtl:pl-[50px] rtl:pr-5">Edit Review</div>
                                                <div className="p-5">
                                                    <form>
                                                        <div className="mb-5">
                                                            <input type="text" value={review._id} hidden />
                                                            <label htmlFor="name">User Name</label>
                                                            <input type="text" value={review.user_name} className="form-input mb-3" readOnly disabled />
                                                            <label htmlFor="name">Review</label>
                                                            <textarea
                                                                id="review"
                                                                rows={6}
                                                                placeholder="Enter Review"
                                                                className="form-input mb-2"
                                                                value={review.review}
                                                                name="review"
                                                                onChange={(e) => changeValue(e)}
                                                            />
                                                            <div className="grid content-center">
                                                                <div className="text-md mb-1">Rating</div>
                                                                <div className="w-1/3">
                                                                    <select className="form-select" name="stars" value={review.stars} onChange={(e) => changeValue(e)}>
                                                                        <option value="1" selected>
                                                                            1
                                                                        </option>
                                                                        <option value="2">2</option>
                                                                        <option value="3">3</option>
                                                                        <option value="4">4</option>
                                                                        <option value="5">5</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <div className="mt-8 flex items-center justify-end">
                                                            <button type="button" className="btn btn-outline-danger" onClick={() => setUpdateReview(false)}>
                                                                Cancel
                                                            </button>
                                                            <button type="button" className="btn btn-primary ltr:ml-4 rtl:mr-4" onClick={saveUpdateReview}>
                                                                Update
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </Dialog.Panel>
                                        </Transition.Child>
                                    </div>
                                </div>
                            </Dialog>
                        </Transition>
                    </>
                )}
        </>
    );
};
export default ProductReview;
