import { setPageTitle } from '@/store/themeConfigSlice';
import { useEffect, useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import Link from 'next/link';
import BillingForm from '@/components/Orders/Form/BillingForm';
import ShippingForm from '@/components/Orders/Form/ShippingForm';
import ItemForm from '@/components/Orders/Form/ItemForm';
import AdjustmentForm from '@/components/Orders/Form/AdjustmentForm';
// import DiscountForm from '@/components/Orders/Form/DiscountForm';
// import MetaForm from '@/components/Orders/Form/MetaForm';
// import CustomMetaForm from '@/components/Orders/Form/CustomMetaForm';
import OrderStatusForm from '@/components/Orders/Form/OrderStatusForm';
import PaymentTypeForm from '@/components/Orders/Form/PaymentTypeForm';
import ShippingMethodForm from '@/components/Orders/Form/ShippingMethodForm';
import TrackingCodeForm from '@/components/Orders/Form/TrackingCodeForm';
import NotesForm from '@/components/Orders/Form/NotesForm';
import GiftCardPreviewForm from '@/components/Orders/Form/GiftCardPreviewForm';
import { SaveOrder } from '@/utils/saveOrder';
import { coloredToast } from '@/lib/toast';
import UserForm from '@/components/Orders/Form/UserForm';
import { useRouter } from 'next/router';
import ProtectedRoute from '@/components/ProtectedRoute';
import { logActivity } from '@/utils/activityLogger';
import { mapAdjustmentsToLegacy, mapLegacyToAdjustments, UnifiedAdjustment } from '@/utils/orderAdjustmentAdapter';
import { calculateOrderTotals } from '@/utils/calculateOrderTotals';
import { useRunningPromotions } from '@/hooks/useRunningPromotions';
import AdminNotes from '@/components/Orders/Form/AdminNotes';

interface OrderProps {
    order: any;
}

const EditOrder: React.FC<OrderProps> = ({ order }) => {
    const [isMounted, setIsMounted] = useState(false);

    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Order Edit'));
        setIsMounted(true);
    }, []);

    const router = useRouter();
    const [orderDate, setOrderDate] = useState<any>(order.order_date);
    const [paymentDate, setPaymentDate] = useState<any>(order.order_payment.payment_date);

    // define user for point
    const [userId, setUserId] = useState(order.user_id);

    // billing state
    const [billing, setBilling] = useState({
        billing_name: order.customer.billing.name || '',
        billing_email: order.customer.billing.email || '',
        billing_phone: order.customer.billing.phone || '',
    });

    // shipping state
    const [shipping, setShipping] = useState({
        shipping_name: order.customer.shipping.name || '',
        shipping_phone: order.customer.shipping.phone || '',
        shipping_address: order.customer.shipping.address || '',
        shipping_province: order.customer.shipping.provinsi || '',
        shipping_city: order.customer.shipping.kota || '',
        shipping_kecamatan: order.customer.shipping.kecamatan || '',
        shipping_kelurahan: order.customer.shipping.kelurahan || '',
        shipping_postcode: order.customer.shipping.kodepos || '',
    });

    // order item state
    const savedOrderItems = order.order_items.map((item: any, index: number) => {
        const attributes = item.attribute_selected ? Object.keys(item.attribute_selected) : [];
        // For gift card, use variation from item.variation or create from gift_card_data.card_id
        let variation = null;
        if (item.is_gift_card) {
            if (item.variation && item.variation.Gift) {
                variation = item.variation;
            } else if (item.gift_card_data && item.gift_card_data.card_id) {
                variation = { Gift: item.gift_card_data.card_id };
            } else {
                variation = { Gift: 'Card 01' }; // Default fallback
            }
        } else {
            variation = item.attribute_selected ? item.attribute_selected : null;
        }

        return {
            id: index,
            item_id: item.product_id || '',
            product_image: item.image || '',
            product_title: item.name || '',
            product_sku: item.sku || '',
            product_url: item.url || '',
            quantity: item.qty || 0,
            amount: item.is_free_item ? 0 : (item.price || 0),
            price: item.price || 0,
            attributes: attributes,
            variation: variation,
            custom_text: item.custom_text || {},
            is_gift_card: item.is_gift_card || false,
            is_free_item: item.is_free_item || false,
            gift_card_data: item.gift_card_data || null,
            click_n_collect: item.clickAndCollectData || null,
        };
    });
    const [items, setItems] = useState<any>(savedOrderItems);

    // shipping method state
    const [shippingMethod, setShippingMethod] = useState({
        provider: order.order_shipment.provider || '',
        service: order.order_shipment.service || '',
        price: order.order_shipment.price || 0,
        tracking_code: order.order_shipment.tracking_code || '',
    });

    const savedDiscountItems = (order.order_voucher || []).map((coupon: any, index: number) => ({
        id: index + 1,
        coupon_name: coupon.voucher || '',
        amount: coupon.amount || 0,
        free_item: coupon.free_item || '',
    }));

    const savedMetaItems = (order.meta_items || []).map((meta: any, index: number) => ({
        id: index + 1,
        key: meta.key || '',
        amount: meta.amount || 0,
        value: meta.value ?? '',
        name: meta.name || '',
        type: meta.type || '',
    }));

    const savedCustomMetaItems = (order.custom_meta_items || []).map((meta: any, index: number) => ({
        id: index + 1,
        key: meta.key || '',
        value: meta.value || '',
    }));

    const [adjustments, setAdjustments] = useState<UnifiedAdjustment[]>(() =>
        mapLegacyToAdjustments(savedDiscountItems, savedMetaItems, savedCustomMetaItems)
    );
    const { promotions, isLoading: isLoadingPromotions } = useRunningPromotions();
    const { discounts, meta, customMeta } = useMemo(() => mapAdjustmentsToLegacy(adjustments), [adjustments]);

    const { subTotal, discountTotal, metaTotal, pointTotal, extraDiscountTotal, birthdayExtraTotal, totalPrice } = useMemo(
        () => calculateOrderTotals(items, shippingMethod.price, discounts, meta),
        [items, shippingMethod.price, discounts, meta]
    );

    const [orderStatus, setOrderStatus] = useState(order.order_status);
    const [orderProceed, setOrderProceed] = useState(order.on_proceed);

    const [paymentType, setPaymentType] = useState({
        payment_code: order.order_payment.payment_code || '',
        name: order.order_payment.name || '',
        acquire: order.order_payment.acquire || '',
        payment_type: order.order_payment.payment_type || '',
        payment_date: order.order_payment.payment_date || '',
    });

    const [notes, setNotes] = useState(order.notes || '');
    const [adminNotes, setAdminNotes] = useState(order.admin_notes || '');
    const [isLoading, setIsLoading] = useState(false);
    const [isLoadingProceed, setIsLoadingProceed] = useState(false);
    const [loadSetPreorder, setLoadSetPreorder] = useState(false);
    const [isPreorder, setIsPreorder] = useState(order.is_preorder);

    const saveOrder = async () => {
        setIsLoading(true);

        const validationSave = SaveOrder(adminNotes, billing, orderDate, paymentDate, shipping, items, shippingMethod, discounts, meta, customMeta, orderStatus, paymentType, totalPrice, notes, userId, adjustments);
        if (validationSave.status === false) {
            setIsLoading(false);
            return;
        }

        // Inline comparison for change tracking
        const changes: string[] = [];
        const compare = (label: string, before: any, after: any) => {
            if (JSON.stringify(before) !== JSON.stringify(after)) {
                if (typeof before === 'string' || typeof before === 'number' || typeof before === 'boolean') {
                    changes.push(`${label}: ${before} → ${after}`);
                } else {
                    changes.push(`${label}: [Changed]`);
                }
            }
        };

        compare('Tanggal Order', order.order_date, orderDate);
        compare('Tanggal Pembayaran', order.order_payment.payment_date, paymentDate);

        compare('Billing - Nama', order.customer.billing.name, billing.billing_name);
        compare('Billing - Email', order.customer.billing.email, billing.billing_email);
        compare('Billing - Telepon', order.customer.billing.phone, billing.billing_phone);

        compare('Shipping - Nama', order.customer.shipping.name, shipping.shipping_name);
        compare('Shipping - Telepon', order.customer.shipping.phone, shipping.shipping_phone);
        compare('Shipping - Alamat', order.customer.shipping.address, shipping.shipping_address);
        compare('Shipping - Provinsi', order.customer.shipping.provinsi, shipping.shipping_province);
        compare('Shipping - Kota', order.customer.shipping.kota, shipping.shipping_city);
        compare('Shipping - Kecamatan', order.customer.shipping.kecamatan, shipping.shipping_kecamatan);
        compare('Shipping - Kodepos', order.customer.shipping.kodepos, shipping.shipping_postcode);
        compare('Shipping - Kelurahan', order.customer.shipping.kelurahan, shipping.shipping_kelurahan);

        compare('Shipping - Provider', order.order_shipment.provider, shippingMethod.provider);
        compare('Shipping - Service', order.order_shipment.service, shippingMethod.service);
        compare('Shipping - Price', order.order_shipment.price, shippingMethod.price);
        compare('Shipping - Tracking', order.order_shipment.tracking_code, shippingMethod.tracking_code);

        compare('Status Order', order.order_status, orderStatus);
        compare('On Proceed', order.on_proceed, orderProceed);
        compare('Is Preorder', order.is_preorder, isPreorder);

        compare('Pembayaran - Code', order.order_payment.payment_code, paymentType.payment_code);
        compare('Pembayaran - Nama', order.order_payment.name, paymentType.name);
        compare('Pembayaran - Acquire', order.order_payment.acquire, paymentType.acquire);
        compare('Pembayaran - Type', order.order_payment.payment_type, paymentType.payment_type);
        compare('Pembayaran - Tanggal', order.order_payment.payment_date, paymentType.payment_date);

        compare('Catatan', order.notes, notes);
        compare('Catatan Admin', order.admin_notes, adminNotes);
        compare('Items', order.order_items, items);
        compare('Discounts', order.order_voucher, discounts);
        compare('Meta', order.meta_items, meta);
        compare('Custom Meta', order.custom_meta_items, customMeta);

        if (changes.length === 0) {
            coloredToast('info', 'Tidak ada perubahan pada order');
            setIsLoading(false);
            return;
        }

        try {
            const api_url = process.env.API_URL;
            const payload = {
                data: validationSave.data,
            };
            // login credential
            const response = await fetch(`${api_url}api/order/update/${order._id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });

            // condition add order failed
            if (!response.ok) {
                const res = await response.json();

                await logActivity({
                    location: 'Edit Order',
                    description: `Gagal mengubah Order - ${order.order_id} '}`,
                });

                if (Array.isArray(res)) {
                    const combinedMessage = res.map((item) => item.message).join('\n\n');
                    coloredToast('warning', combinedMessage);
                } else {
                    coloredToast('warning', res.message);
                }
                setIsLoading(false);
                return;
            }

            await logActivity({
                location: 'Edit Orders',
                description: `Perubahan pada Order - ${order.order_id} , Changes :  \n${changes.join(' | ')}`,
            });

            coloredToast('success', 'order updated successfully');
            router.push('/orders');
        } catch (error) {
            console.error(error);
            await logActivity({
                location: 'Edit Orders',
                description: `Gagal mengubah Order - ${order.order_id}`,
            });
            coloredToast('danger', 'something went wrong');
        }

        setIsLoading(false);
    };
    const setProceed = async () => {
        setIsLoadingProceed(true);

        try {
            const api_url = process.env.API_URL;

            // login credential
            const response = await fetch(`${api_url}api/order/set-proceed/`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
                body: JSON.stringify({ order_id: order.order_id }),
            });

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

                setIsLoadingProceed(false);
                return;
            }
            setOrderProceed(true);
            coloredToast('success', 'set proceed successfully');
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'something went wrong');
        }

        setIsLoadingProceed(false);
    };

    const setPreorder = async () => {
        setLoadSetPreorder(true);

        try {
            const api_url = process.env.API_URL;

            const url = isPreorder ? 'unset-preorder' : 'set-preorder';

            // login credential
            const response = await fetch(`${api_url}api/order/${url}/${order._id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });

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

                setIsLoadingProceed(false);
                return;
            }
            setIsPreorder(!isPreorder);
            coloredToast('success', `${isPreorder ? 'unset' : 'set'} preorder successfully`);
        } catch (error) {
            console.error(error);
            coloredToast('danger', 'something went wrong');
        }

        setLoadSetPreorder(false);
    };

    return (
        <>
            {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <Link href="/orders" className="text-primary hover:underline">
                                        Orders
                                    </Link>
                                </li>
                                <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                                    <span>edit</span>
                                </li>
                            </ul>
                        </div>
                        <div className="flex flex-col gap-2.5 xl:flex-row">
                            <div className="panel flex-1 px-0 py-6 ltr:xl:mr-6 rtl:xl:ml-6">
                                <div className="text-center font-bold">ORDER ID : {order.order_id}</div>
                                <hr className="my-6 border-white-light dark:border-[#1b2e4b]" />
                                <BillingForm billing={billing} setBilling={setBilling} orderDate={orderDate} setOrderDate={setOrderDate} paymentDate={paymentDate} setPaymentDate={setPaymentDate} />
                                <hr className="my-6 border-white-light dark:border-[#1b2e4b]" />
                                <div className="mt-8 px-4">
                                    <ShippingForm shipping={shipping} setShipping={setShipping} />
                                </div>

                                <div className="mt-8">
                                    <ItemForm items={items} setItems={setItems} order_status={order.order_status} promotions={promotions} />
                                    {order.free_item && <div className=" border-1 my-3 bg-cyan-800 p-2 text-center font-bold italic text-white">Free Item : {order.free_item}</div>}
                                    <ShippingMethodForm shippingMethod={shippingMethod} setShippingMethod={setShippingMethod} order_status={order.order_status} />
                                    <AdjustmentForm
                                        adjustments={adjustments}
                                        setAdjustments={setAdjustments}
                                        items={items}
                                        setItems={setItems}
                                        order_status={orderStatus}
                                        userId={userId}
                                        promotions={promotions}
                                        isLoadingPromotions={isLoadingPromotions}
                                    />
                                    {/*
                                    <DiscountForm discounts={discounts} setDiscounts={setDiscounts} order_status={order.order_status} />
                                    <MetaForm meta={meta} setMeta={setMeta} order_status={order.order_status} />
                                    <CustomMetaForm customMeta={customMeta} setCustomMeta={setCustomMeta} />
                                    */}
                                    <div className="mt-8 flex flex-col justify-between px-4 sm:flex-row">
                                        <div className="mb-4  sm:mb-0"></div>
                                        <div className="sm:w-2/5">
                                            <div className="flex items-center justify-between">
                                                <div>Subtotal</div>
                                                <div>Rp {subTotal.toLocaleString('id-ID')}</div>
                                            </div>

                                            <div className="mt-4 flex items-center justify-between">
                                                <div>Shipping </div>
                                                <div>Rp {shippingMethod.price.toLocaleString('id-ID')}</div>
                                            </div>
                                            {discountTotal > 0 && (
                                                <div className="mt-4 flex items-center justify-between">
                                                    <div>Discount</div>
                                                    <div>Rp -{discountTotal.toLocaleString('id-ID')}</div>
                                                </div>
                                            )}
                                            {extraDiscountTotal > 0 && (
                                                <div className="mt-4 flex items-center justify-between">
                                                    <div>Extra Discount</div>
                                                    <div>Rp -{extraDiscountTotal.toLocaleString('id-ID')}</div>
                                                </div>
                                            )}
                                            {birthdayExtraTotal > 0 && (
                                                <div className="mt-4 flex items-center justify-between">
                                                    <div>Birthday Extra</div>
                                                    <div>Rp -{birthdayExtraTotal.toLocaleString('id-ID')}</div>
                                                </div>
                                            )}
                                            {pointTotal > 0 && (
                                                <div className="mt-4 flex items-center justify-between">
                                                    <div>Point</div>
                                                    <div>Rp -{pointTotal.toLocaleString('id-ID')}</div>
                                                </div>
                                            )}
                                            {metaTotal > 0 && (
                                                <div className="mt-4 flex items-center justify-between">
                                                    <div>Additional Fee</div>
                                                    <div>Rp {metaTotal.toLocaleString('id-ID')}</div>
                                                </div>
                                            )}
                                            <div className="mt-4 flex items-center justify-between font-semibold">
                                                <div>TOTAL</div>
                                                <div>Rp {totalPrice.toLocaleString('id-ID')}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <NotesForm notes={notes} setNotes={setNotes} />
                            </div>
                            <div className="mt-6 w-full xl:mt-0 xl:w-96">
                                <OrderStatusForm orderStatus={orderStatus} setOrderStatus={setOrderStatus} />
                                <UserForm userId={userId} setUserId={setUserId} setBilling={setBilling} setShipping={setShipping} />
                                <PaymentTypeForm paymentType={paymentType} setPaymentType={setPaymentType} />
                                <TrackingCodeForm shippingMethod={shippingMethod} setShippingMethod={setShippingMethod} />
                                <AdminNotes adminNotes={adminNotes} setAdminNotes={setAdminNotes} />

                                <GiftCardPreviewForm items={items} orderId={order.order_id} />

                                <div className="panel">
                                    <div className="mb-3 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                                        <Link href={`/orders/packing-slip/${order.order_id}`} target="_blank" className="flex hover:text-info">
                                            <button type="button" className="btn btn-secondary w-full gap-2">
                                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path
                                                        d="M3 10C3 6.22876 3 4.34315 4.17157 3.17157C5.34315 2 7.22876 2 11 2H13C16.7712 2 18.6569 2 19.8284 3.17157C21 4.34315 21 6.22876 21 10V14C21 17.7712 21 19.6569 19.8284 20.8284C18.6569 22 16.7712 22 13 22H11C7.22876 22 5.34315 22 4.17157 20.8284C3 19.6569 3 17.7712 3 14V10Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                    />
                                                    <path d="M8 12H16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    <path d="M8 8H16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    <path d="M8 16H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                </svg>
                                                Packing Slip
                                            </button>
                                        </Link>
                                    </div>
                                    {orderStatus === 'Processing' && (
                                        <>
                                            {!orderProceed ? (
                                                <div className="mb-3 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                                                    <button type="button" disabled={isLoadingProceed} onClick={setProceed} className="btn btn-info w-full gap-2">
                                                        {isLoadingProceed ? (
                                                            <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                                        ) : (
                                                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                <path
                                                                    fillRule="evenodd"
                                                                    clipRule="evenodd"
                                                                    d="M7.26279 3.25871C7.38317 2.12953 8.33887 1.25 9.5 1.25H14.5C15.6611 1.25 16.6168 2.12953 16.7372 3.25871C17.5004 3.27425 18.1602 3.31372 18.7236 3.41721C19.4816 3.55644 20.1267 3.82168 20.6517 4.34661C21.2536 4.94853 21.5125 5.7064 21.6335 6.60651C21.75 7.47348 21.75 8.5758 21.75 9.94339V16.0531C21.75 17.4207 21.75 18.523 21.6335 19.39C21.5125 20.2901 21.2536 21.048 20.6517 21.6499C20.0497 22.2518 19.2919 22.5107 18.3918 22.6317C17.5248 22.7483 16.4225 22.7483 15.0549 22.7483H8.94513C7.57754 22.7483 6.47522 22.7483 5.60825 22.6317C4.70814 22.5107 3.95027 22.2518 3.34835 21.6499C2.74643 21.048 2.48754 20.2901 2.36652 19.39C2.24996 18.523 2.24998 17.4207 2.25 16.0531V9.94339C2.24998 8.5758 2.24996 7.47348 2.36652 6.60651C2.48754 5.7064 2.74643 4.94853 3.34835 4.34661C3.87328 3.82168 4.51835 3.55644 5.27635 3.41721C5.83977 3.31372 6.49963 3.27425 7.26279 3.25871ZM7.26476 4.75913C6.54668 4.77447 5.99332 4.81061 5.54735 4.89253C4.98054 4.99664 4.65246 5.16382 4.40901 5.40727C4.13225 5.68403 3.9518 6.07261 3.85315 6.80638C3.75159 7.56173 3.75 8.56285 3.75 9.99826V15.9983C3.75 17.4337 3.75159 18.4348 3.85315 19.1901C3.9518 19.9239 4.13225 20.3125 4.40901 20.5893C4.68577 20.866 5.07435 21.0465 5.80812 21.1451C6.56347 21.2467 7.56458 21.2483 9 21.2483H15C16.4354 21.2483 17.4365 21.2467 18.1919 21.1451C18.9257 21.0465 19.3142 20.866 19.591 20.5893C19.8678 20.3125 20.0482 19.9239 20.1469 19.1901C20.2484 18.4348 20.25 17.4337 20.25 15.9983V9.99826C20.25 8.56285 20.2484 7.56173 20.1469 6.80638C20.0482 6.07261 19.8678 5.68403 19.591 5.40727C19.3475 5.16382 19.0195 4.99664 18.4527 4.89253C18.0067 4.81061 17.4533 4.77447 16.7352 4.75913C16.6067 5.87972 15.655 6.75 14.5 6.75H9.5C8.345 6.75 7.39326 5.87972 7.26476 4.75913ZM9.5 2.75C9.08579 2.75 8.75 3.08579 8.75 3.5V4.5C8.75 4.91421 9.08579 5.25 9.5 5.25H14.5C14.9142 5.25 15.25 4.91421 15.25 4.5V3.5C15.25 3.08579 14.9142 2.75 14.5 2.75H9.5ZM15.5483 10.4883C15.8309 10.7911 15.8146 11.2657 15.5117 11.5483L11.226 15.5483C10.9379 15.8172 10.4907 15.8172 10.2025 15.5483L8.48826 13.9483C8.18545 13.6657 8.16908 13.1911 8.45171 12.8883C8.73433 12.5854 9.20893 12.5691 9.51174 12.8517L10.7143 13.9741L14.4883 10.4517C14.7911 10.1691 15.2657 10.1854 15.5483 10.4883Z"
                                                                    fill="currentColor"
                                                                />
                                                            </svg>
                                                        )}
                                                        Set Proceed
                                                    </button>
                                                </div>
                                            ) : (
                                                <div className="mb-3">
                                                    <div className=" flex items-center justify-center">
                                                        <div className="mr-3 h-2 w-2 rounded-full bg-primary"></div>
                                                        <div className="font-semibold text-primary">Proceed</div>
                                                    </div>
                                                </div>
                                            )}
                                        </>
                                    )}

                                    <div className="mb-3 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                                        <button type="button" disabled={isLoading} onClick={saveOrder} className="btn btn-success w-full gap-2">
                                            {isLoading ? (
                                                <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                            ) : (
                                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 shrink-0 ltr:mr-2 rtl:ml-2">
                                                    <path
                                                        d="M3.46447 20.5355C4.92893 22 7.28595 22 12 22C16.714 22 19.0711 22 20.5355 20.5355C22 19.0711 22 16.714 22 12C22 11.6585 22 11.4878 21.9848 11.3142C21.9142 10.5049 21.586 9.71257 21.0637 9.09034C20.9516 8.95687 20.828 8.83317 20.5806 8.58578L15.4142 3.41944C15.1668 3.17206 15.0431 3.04835 14.9097 2.93631C14.2874 2.414 13.4951 2.08581 12.6858 2.01515C12.5122 2 12.3415 2 12 2C7.28595 2 4.92893 2 3.46447 3.46447C2 4.92893 2 7.28595 2 12C2 16.714 2 19.0711 3.46447 20.5355Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                    />
                                                    <path
                                                        d="M17 22V21C17 19.1144 17 18.1716 16.4142 17.5858C15.8284 17 14.8856 17 13 17H11C9.11438 17 8.17157 17 7.58579 17.5858C7 18.1716 7 19.1144 7 21V22"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                    />
                                                    <path opacity="0.5" d="M7 8H13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                </svg>
                                            )}
                                            Save
                                        </button>
                                    </div>

                                    <div className="mb-3 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-1">
                                        <button type="button" disabled={loadSetPreorder} onClick={setPreorder} className={`btn btn-outline-${isPreorder ? 'warning' : 'info'} w-full gap-2`}>
                                            {loadSetPreorder ? (
                                                <span className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white border-l-transparent align-middle ltr:mr-4 rtl:ml-4"></span>
                                            ) : (
                                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path
                                                        d="M2 12C2 8.22876 2 6.34315 3.17157 5.17157C4.34315 4 6.22876 4 10 4H14C17.7712 4 19.6569 4 20.8284 5.17157C22 6.34315 22 8.22876 22 12V14C22 17.7712 22 19.6569 20.8284 20.8284C19.6569 22 17.7712 22 14 22H10C6.22876 22 4.34315 22 3.17157 20.8284C2 19.6569 2 17.7712 2 14V12Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                    />
                                                    <path opacity="0.5" d="M7 4V2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    <path opacity="0.5" d="M17 4V2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    <path opacity="0.5" d="M2 9H22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                                                    <path d="M9 14.5L10.5 13V17" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                                    <path
                                                        d="M13 16V14C13 13.4477 13.4477 13 14 13C14.5523 13 15 13.4477 15 14V16C15 16.5523 14.5523 17 14 17C13.4477 17 13 16.5523 13 16Z"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        strokeLinecap="round"
                                                    />
                                                </svg>
                                            )}
                                            {isPreorder ? 'Unset' : 'Set'} Preorder
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </>
                )}
        </>
    );
};

export default EditOrder;

export const getServerSideProps = async (context: any) => {
    try {
        const { params } = context;
        const { order } = params;

        const api_url = process.env.API_URL;

        const response = await fetch(`${api_url}api/order/${order}`, {
            headers: {
                cookie: context.req.headers.cookie || '',
            },
        });

        if (!response.ok) {
            return {
                notFound: true,
            };
        }
        const data = await response.json();

        return {
            props: {
                order: data,
            },
        };
    } catch (err) {
        return {
            notFound: true,
        };
    }
};
