import { Tab } from '@headlessui/react';
import { Fragment, useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import Link from 'next/link';
import { useDispatch } from 'react-redux';

import { setPageTitle } from '@/store/themeConfigSlice';

const AllOrders = dynamic(() => import('@/components/Orders/AllOrders'), { ssr: false });
const PendingOrders = dynamic(() => import('@/components/Orders/PendingOrders'), { ssr: false });
const ProcessingOrders = dynamic(() => import('@/components/Orders/ProcessingOrders'), { ssr: false });
const IndeliveryOrders = dynamic(() => import('@/components/Orders/IndeliveryOrders'), { ssr: false });
const CompletedOrders = dynamic(() => import('@/components/Orders/CompletedOrders'), { ssr: false });
const FailedOrders = dynamic(() => import('@/components/Orders/FailedOrders'), { ssr: false });
const CanceledOrders = dynamic(() => import('@/components/Orders/CanceledOrders'), { ssr: false });
const OrderIndex = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Order'));
    }, []);

    const savedTab = typeof window !== 'undefined' ? localStorage.getItem('orderTab') : null;

    const [isMounted, setIsMounted] = useState(false);
    const [selectedIndex, setSelectedIndex] = useState(savedTab ? parseInt(savedTab, 10) : 0);

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

    // Save state to localStorage whenever there is a change
    useEffect(() => {
        localStorage.setItem('orderTab', selectedIndex.toString());
    }, [selectedIndex]);

    const [orderCountStatus, setOrderCountStatus] = useState<any>({
        pending: 0,
        processing: 0,
        indelivery: 0,
        completed: 0,
        failed: 0,
        canceled: 0,
    });

    const fetchDataCount = async () => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/order/order-count`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const res = await response.json();
            setOrderCountStatus(() => {
                return {
                    pending: res.data.Pending,
                    processing: res.data.Processing,
                    indelivery: res.data.InDelivery,
                    completed: res.data.Completed,
                    failed: res.data.Failed,
                    canceled: res.data.Canceled,
                };
            });
        } catch (error) {}
    };
    // useEffect(() => {
    //     fetchDataCount();
    // }, []);

    useEffect(() => {
        fetchDataCount();
    }, [selectedIndex]);

    return (
        <>
            {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <span>Orders</span>
                                </li>
                            </ul>
                        </div>
                        <div className="mb-5 flex items-center gap-2">
                            <Link href="/orders/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 Order
                            </Link>
                        </div>
                        <Tab.Group selectedIndex={selectedIndex} onChange={setSelectedIndex}>
                            <Tab.List className="mt-3 flex w-full floating-menu">
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-primary text-primary !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 before:inline-block hover:border-primary hover:text-primary dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            All
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-warning !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-warning before:inline-block hover:border-warning hover:text-warning dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none">
                                                <path
                                                    d="M2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                />
                                                <path opacity="0.5" d="M12 9V13H16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                <circle opacity="0.5" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeDasharray="0.5 3.5" />
                                            </svg>
                                            <span className="ms-2">Pending</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.pending})</span>
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-primary !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-primary before:inline-block hover:border-primary hover:text-primary dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none">
                                                <path
                                                    opacity="0.5"
                                                    d="M12 12L9.0423 14.9289C6.11981 17.823 4.65857 19.27 5.06765 20.5185C5.10282 20.6258 5.14649 20.7302 5.19825 20.8307C5.80046 22 7.86697 22 12 22C16.133 22 18.1995 22 18.8017 20.8307C18.8535 20.7302 18.8972 20.6258 18.9323 20.5185C19.3414 19.27 17.8802 17.823 14.9577 14.9289L12 12ZM12 12L14.9577 9.07107C17.8802 6.177 19.3414 4.72997 18.9323 3.48149C18.8972 3.37417 18.8535 3.26977 18.8017 3.16926C18.1995 2 16.133 2 12 2C7.86697 2 5.80046 2 5.19825 3.16926C5.14649 3.26977 5.10282 3.37417 5.06765 3.48149C4.65857 4.72997 6.11981 6.177 9.0423 9.07107L12 12Z"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                />
                                                <path d="M10 5.5H14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                <path d="M10 18.5H14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                            </svg>
                                            <span className="ms-2">Processing</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.processing})</span>
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-info !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-info before:inline-block hover:border-info hover:text-info dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none">
                                                <rect x="16" y="13" width="6" height="6" rx="3" stroke="#1C274C" strokeWidth="1.5" />
                                                <path
                                                    d="M11 16V14.5C11 12.6144 11 11.6716 10.4142 11.0858C9.82843 10.5 8.88562 10.5 7 10.5H6.4C6.02856 10.5 5.84284 10.5 5.68616 10.5123C3.72466 10.6667 2.1667 12.2247 2.01233 14.1862C2 14.3428 2 14.5286 2 14.9C2 14.9929 2 15.0393 2.00308 15.0785C2.04168 15.5688 2.43116 15.9583 2.92154 15.9969C2.96071 16 3.00714 16 3.1 16H11ZM11 16H16"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                />
                                                <path
                                                    opacity="0.5"
                                                    d="M9.5 16C9.5 17.6569 8.15685 19 6.5 19C4.84315 19 3.5 17.6569 3.5 16"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                />
                                                <path
                                                    d="M12 5H12.5279C13.7307 5 14.3321 5 14.8154 5.2987C15.2987 5.5974 15.5677 6.13531 16.1056 7.21114L19 13"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                />
                                                <path
                                                    opacity="0.5"
                                                    d="M18.1426 11L18.8243 10.4978C19.0871 10.3041 19.2186 10.2073 19.31 10.0811C19.3722 9.99519 19.4203 9.89994 19.4526 9.7989C19.5 9.65046 19.5 9.48721 19.5 9.16072C19.5 8.54327 19.5 8.23455 19.3684 8.00405C19.2797 7.84887 19.1511 7.72028 18.996 7.63165C18.7654 7.5 18.4567 7.5 17.8393 7.5H16.5"
                                                    stroke="#1C274C"
                                                    strokeWidth="1.5"
                                                    strokeLinecap="round"
                                                />
                                            </svg>
                                            <span className="ms-2">In Delivery</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.indelivery})</span>
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-success !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-success before:inline-block hover:border-success hover:text-success dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" 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="M8.5 12.5L10.5 14.5L15.5 9.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                            </svg>
                                            <span className="ms-2">Completed</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.completed})</span>
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-danger !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-danger before:inline-block hover:border-danger hover:text-danger dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none">
                                                <path opacity="0.5" d="M18.5 5.5L5.50002 18.4998" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                <path
                                                    d="M22 10.8489V13.1511C22 14.3773 22 14.9905 21.7716 15.5418C21.5433 16.0931 21.1097 16.5266 20.2426 17.3937L17.3937 20.2426C16.5266 21.1097 16.0931 21.5433 15.5418 21.7716C14.9905 22 14.3773 22 13.1511 22H10.8489C9.62267 22 9.00954 22 8.45823 21.7716C7.90691 21.5433 7.47337 21.1097 6.60628 20.2426L3.75736 17.3937C2.89027 16.5266 2.45672 16.0931 2.22836 15.5418C2 14.9905 2 14.3773 2 13.1511V10.8489C2 9.62267 2 9.00954 2.22836 8.45823C2.45672 7.90691 2.89027 7.47337 3.75736 6.60628L6.60628 3.75736C7.47337 2.89027 7.90691 2.45672 8.45823 2.22836C9.00954 2 9.62267 2 10.8489 2H13.1511C14.3773 2 14.9905 2 15.5418 2.22836C16.0931 2.45672 16.5266 2.89027 17.3937 3.75736L20.2426 6.60628C21.1097 7.47337 21.5433 7.90691 21.7716 8.45823C22 9.00954 22 9.62267 22 10.8489Z"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                />
                                            </svg>
                                            <span className="ms-2">Failed</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.failed})</span>
                                        </button>
                                    )}
                                </Tab>
                                <Tab as={Fragment}>
                                    {({ selected }) => (
                                        <button
                                            className={`${
                                                selected ? '!border-dark !bg-white !outline-none dark:!bg-[#191e3a]' : ''
                                            } flex flex-1 items-center justify-center border-t-2 border-transparent bg-primary-light p-7 py-3 text-dark before:inline-block hover:border-dark hover:text-dark dark:bg-transparent dark:hover:bg-[#191e3a]`}
                                        >
                                            <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" 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="#1C274C"
                                                    strokeWidth="1.5"
                                                />
                                                <path d="M14.5 9.50002L9.5 14.5M9.49998 9.5L14.5 14.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                            </svg>
                                            <span className="ms-2">Canceled</span>
                                            <span className="ms-1 text-xs">({orderCountStatus.canceled})</span>
                                        </button>
                                    )}
                                </Tab>
                            </Tab.List>
                            <Tab.Panels>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 0 && <AllOrders />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 1 && <PendingOrders />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 2 && <ProcessingOrders fetchCount={fetchDataCount} />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 3 && <IndeliveryOrders fetchCount={fetchDataCount} />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 4 && <CompletedOrders />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 5 && <FailedOrders />}</div>
                                </Tab.Panel>
                                <Tab.Panel>
                                    <div className="pt-5">{selectedIndex === 6 && <CanceledOrders />}</div>
                                </Tab.Panel>
                            </Tab.Panels>
                        </Tab.Group>
                    </>
                )}
        </>
    );
};

export default OrderIndex;
