'use client';

import AnimatedBottomSheet from '@/components/bottomsheet/AnimatedBottomSheet';
import Button from '@/components/button/PrimaryButton';
import { ChevronLeft } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useCheckoutStore } from '../../store/Store';
import { toast } from '@/components/Toast';
import { useCreateOrder } from '../../hooks/useOrderData';
import { extractErrorMessage } from '@/lib/func';
import { useParams } from 'next/navigation';
import { useGetCartItems, useSaveAllMethod } from '@/app/[name]/(Dialogs)/cart/hooks/useCartData';
import { useGetProfile } from '@/app/[name]/(Profile)/profile/hooks/userProfileData';
import { useCallback, useMemo } from 'react';
import { useGetShipmentMethod } from '../../hooks/useOrderData';
import { useGetProducts } from '@/app/[name]/(Main)/hooks/useMenuData';
import { isVariablePricing } from '@/app/[name]/(Main)/types/Types';
import CartItemsList from '@/app/[name]/(Dialogs)/cart/components/CartItemsList';
import { useCartStore } from '@/app/[name]/(Dialogs)/cart/store/Store';

type SummarySectionProps = {
    cartModal: boolean;
    onToggleCartModal: () => void;
    deliveryType: string;
};

export const SummarySection = ({ cartModal, onToggleCartModal, deliveryType }: SummarySectionProps) => {

    const { t } = useTranslation('parallels', { keyPrefix: 'OrderDetail' });
    const { isSelectedShipment, isSelectedPayment, deliveryType: storeDeliveryType, paymentType, selectedAddressId, tableNumber, carAddress, clear } = useCheckoutStore();
    const { description, reset: resetCart } = useCartStore();
    const { mutate: createOrder, isPending: isCreateOrderPending } = useCreateOrder();
    const { mutate: saveAllMethod, isPending: isSaveAllMethodPending } = useSaveAllMethod()
    const params = useParams();
    const name = params.name as string;
    const { isSuccess } = useGetProfile();
    const { data: cartData } = useGetCartItems(isSuccess);
    const { data: productsResponse } = useGetProducts();
    const { data: shipmentMethod } = useGetShipmentMethod();

    const hasVariablePricingItem = useMemo(() => {
        const cartItems = cartData?.data?.items;
        const products = productsResponse?.data;
        if (!cartItems?.length || !products?.length) return false;

        return cartItems.some((item) => {
            const product = products.find((p) =>
                p.variants?.some((v) => String(v.id) === String(item.variantId))
            );
            return product != null && isVariablePricing(product);
        });
    }, [cartData?.data?.items, productsResponse?.data]);

    const selectedDeliveryMethod = useMemo(() => {
        if (!shipmentMethod?.data || !deliveryType) return null;
        return shipmentMethod.data.find((item) => item.id === deliveryType);
    }, [shipmentMethod?.data, deliveryType]);

    const isCourierDelivery = useMemo(() => {
        return selectedDeliveryMethod?.method === 'deliveryCourier';
    }, [selectedDeliveryMethod]);

    const isDeliveryCar = useMemo(() => {
        return selectedDeliveryMethod?.method === 'deliveryCar';
    }, [selectedDeliveryMethod]);

    const isDineIn = useMemo(() => {
        return selectedDeliveryMethod?.method === 'dineIn';
    }, [selectedDeliveryMethod]);

    const formatPrice = useCallback(
        (value: number) => value.toLocaleString('fa-IR'),
        []
    );

    const subTotal = cartData?.data?.subTotal ?? 0;
    const deliveryFee = cartData?.data?.deliveryFee ?? 0;
    const totalDiscount = cartData?.data?.totalDiscount ?? 0;
    const tax = cartData?.data?.tax ?? 0;
    const total = cartData?.data?.total ?? 0;

    const handleSubmit = () => {
        console.log('sele', storeDeliveryType);

        // if (!isSelectedAddress && isSelectedShipment && isCourierDelivery) {
        //     toast('لطفا آدرس را انتخاب کنید', 'error');
        //     return;
        // }
        if (!isSelectedShipment) {
            toast('لطفا روش تحویل را انتخاب کنید', 'error');
            return;
        }
        if (!isSelectedPayment) {
            toast('لطفا روش پرداخت را انتخاب کنید', 'error');
            return;
        }

        if (isDeliveryCar) {
            if (!carAddress || !carAddress.carModel || !carAddress.carColor || !carAddress.plateNumber) {
                toast('لطفا اطلاعات خودرو را تکمیل کنید', 'error');
                return;
            }
        }

        if (!storeDeliveryType || storeDeliveryType === '0' || !paymentType || paymentType === '0') {
            toast('لطفا تمام اطلاعات را تکمیل کنید', 'error');
            return;
        }

        // if (!isDeliveryCar && !isDineIn && !selectedAddressId) {
        //     toast('لطفا آدرس را انتخاب کنید', 'error');
        //     return;
        // }

        const saveAllMethodData = {
            description: description || '',
            deliveryMethodId: storeDeliveryType,
            paymentMethodId: paymentType,
            tableNumber: isDineIn ? tableNumber.toString() : undefined,
            ...(isCourierDelivery && selectedAddressId && { addressId: selectedAddressId }),
            ...(isDeliveryCar && carAddress && { carAddress }),
        };
        saveAllMethod(saveAllMethodData, {
            onSuccess: () => {
                const orderData: {
                    deliveryMethodId?: string;
                    paymentMethodId?: string;
                    addressId?: string;
                    tableNumber?: number;
                } = {};

                if (storeDeliveryType && storeDeliveryType !== '0') {
                    orderData.deliveryMethodId = storeDeliveryType;
                }
                if (paymentType && paymentType !== '0') {
                    orderData.paymentMethodId = paymentType;
                }
                if (isCourierDelivery && selectedAddressId) {
                    orderData.addressId = selectedAddressId;
                }
                if (isDineIn && tableNumber) {
                    const numTableNumber = Number(tableNumber);
                    if (numTableNumber > 0 && !isNaN(numTableNumber)) {
                        orderData.tableNumber = numTableNumber;
                    }
                }
                createOrder(orderData, {
                    onSuccess: (data) => {
                        clear();
                        resetCart();
                        if (!hasVariablePricingItem && data?.data?.paymentUrl) {
                            window.location.href = data.data.paymentUrl;
                            toast('در حال ریدایرکت به صفحه پرداخت...', 'success');
                        } else {
                            window.location.href = `/${name}/order/track/${data?.data?.order?.id}`;
                            toast('سفارش با موفقیت ثبت شد', 'success');
                        }
                    },
                    onError: (error) => {
                        toast(extractErrorMessage(error), 'error');
                    }
                });
            },
            onError: (error) => {
                toast(extractErrorMessage(error), 'error');
            }
        });
    };

    return (
        <>
            <section className="pb-24">
                <div className="py-3">
                    <div className='w-full flex justify-between items-center gap-2'>
                        <h3 className="text-sm2 font-medium leading-5 inline-block">{t("SectionSummary.Title")}</h3>
                        <button
                            className='text-sm2 text-primary cursor-pointer dark:text-foreground'
                            onClick={onToggleCartModal}
                        >
                            {t("SectionSummary.ButtonViewCart")}
                            <ChevronLeft className='inline-block mr-1 mb-0.5 stroke-primary dark:stroke-foreground' size='16' />
                        </button>
                    </div>
                    <div className='mt-6 text-sm2 grid grid-cols-2 gap-4'>
                        <span className=''>{t("SectionSummary.SumOfItemsLabel")}</span>
                        <span className='font-medium place-self-end '>{formatPrice(subTotal)} T</span>
                        <span className=''>{t("SectionSummary.DeliveryLabel")}</span>
                        <span className='font-medium place-self-end '>{deliveryFee === 0 ? 'رایگان' : formatPrice(deliveryFee) + ' T'}</span>
                        {totalDiscount > 0 && (
                            <>
                                <span className=''>{t("SectionSummary.DiscountLabel")}</span>
                                <span className='font-medium place-self-end '>{formatPrice(totalDiscount)} T</span>
                            </>
                        )}
                        {tax > 0 && (
                            <>
                                <span className=''>{t("SectionSummary.TaxLabel")}</span>
                                <span className='font-medium place-self-end '>{formatPrice(tax)} T</span>
                            </>
                        )}
                        <span className='font-medium '>{t("SectionSummary.TotalLabel")}</span>
                        <span className='font-bold  place-self-end'>{formatPrice(total)} T</span>
                    </div>
                </div>
                <div className='fixed bottom-0 left-0 right-0 z-50 bg-white dark:bg-background border-t border-border p-4 w-full'>
                    <div className='flex justify-between items-center gap-4'>
                        <div className='flex flex-col'>
                            <div className='text-xs text-gray-400 dark:text-gray-500'>{t("PayableAmountLabel")}</div>
                            <div className='text-sm mt-2 font-semibold'>{formatPrice(total)} تومان</div>
                        </div>
                        <Button pending={isCreateOrderPending || isSaveAllMethodPending} onClick={handleSubmit} className='px-10 w-fit dark:bg-white dark:text-black! dark:hover:bg-gray-100'>
                            {hasVariablePricingItem ? t("ButtonRegister") : t("ButtonSubmit")}
                        </Button>
                    </div>
                </div>
            </section>

            <AnimatedBottomSheet
                title={t("CartModal.Title")}
                visible={cartModal}
                onClick={onToggleCartModal}
                titlePadding='ps-5 pe-5'
            >
                <div className='overflow-y-auto noscrollbar px-4 mt-4' dir='rtl'>
                    <CartItemsList />
                </div>
            </AnimatedBottomSheet>
        </>
    );
};

