'use client';

import useToggle from '@/hooks/helpers/useToggle';
import React, { useCallback, useEffect, useMemo } from 'react';
import { AddressSection } from './components/AddressSection';
import { CarAddressSection } from './components/CarAddressSection';
import { CheckoutHeader } from './components/CheckoutHeader';
import { CouponSection } from './components/CouponSection';
import { PaymentSection } from './components/PaymentSection';
import { ShippingSection } from './components/ShippingSection';
import { SummarySection } from './components/SummarySection';
import { TableSection } from './components/TableSection';
import { useGetShipmentMethod } from '../hooks/useOrderData';
import { useGetCartItems } from '@/app/[name]/(Main)/cart/hooks/useCartData';
import { useGetProfile } from '@/app/[name]/(Profile)/profile/hooks/userProfileData';
import { useCheckoutStore } from '../store/Store';

function OrderDetailInex() {
    const { isSuccess } = useGetProfile();
    const { data: cartItems } = useGetCartItems(isSuccess);
    const { state: cartModal, toggle: toggleCartModal } = useToggle();
    const { data: shipmentMethod } = useGetShipmentMethod();
    const {
        deliveryType,
        setDeliveryType,
        paymentType,
        setPaymentType,
        tableNumber,
        setTableNumber,
        setSelectedAddressId,
        setIsSelectedAddress,
        setIsSelectedPayment,
        setIsSelectedShipment,
    } = useCheckoutStore();
    const [couponType, setCouponType] = React.useState<string>('0');
    const [couponCode, setCouponCode] = React.useState<string>('');
    const [couponCodeError, setCouponCodeError] = React.useState<string>('');

    const incrementTableNumber = () => setTableNumber(tableNumber + 1);
    const decrementTableNumber = () => setTableNumber(Math.max(0, tableNumber - 1));

    const changeDeliveryType = useCallback((id: string) => {
        setDeliveryType(id);
    }, [setDeliveryType]);

    const changePaymentType = useCallback((id: string) => {
        setPaymentType(id);
    }, [setPaymentType]);

    const changeCouponType = useCallback((id: string) => {
        setCouponCode('');
        setCouponCodeError('');
        setCouponType(id);
    }, []);

    const changeCouponCode = useCallback((value: string) => {
        setCouponCode(value);
    }, []);

    useEffect(() => {
        if (cartItems?.data?.deliveryMethodId) {
            setDeliveryType(cartItems.data.deliveryMethodId);
            setIsSelectedShipment(true);
        }
    }, [cartItems?.data?.deliveryMethodId, setDeliveryType, setIsSelectedShipment]);

    useEffect(() => {
        if (cartItems?.data?.paymentMethodId) {
            setPaymentType(cartItems.data.paymentMethodId);
            setIsSelectedPayment(true);
        }
    }, [cartItems?.data?.paymentMethodId, setPaymentType, setIsSelectedPayment]);

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

    useEffect(() => {
        if (cartItems?.data?.addressId && selectedDeliveryMethod?.method === 'deliveryCourier') {
            const addressId = cartItems.data.addressId;
            setIsSelectedAddress(true);
            setSelectedAddressId(addressId ?? null);
        }
    }, [cartItems?.data?.addressId, setIsSelectedAddress, setSelectedAddressId, selectedDeliveryMethod]);

    useEffect(() => {
        if (cartItems?.data?.coupon?.couponCode && cartItems.data.couponDiscount > 0) {
            setCouponCode(cartItems.data.coupon.couponCode);
        }
    }, [cartItems?.data?.coupon?.couponCode, cartItems?.data?.couponDiscount]);

    return (
        <div className='h-full bg-background -mx-6 -mt-4 -mb-6 px-6 pt-4 pb-6 flex flex-col gap-5'>
            <CheckoutHeader />

            <ShippingSection
                deliveryType={deliveryType}
                onDeliveryTypeChange={changeDeliveryType}
            />

            {selectedDeliveryMethod?.method === 'deliveryCar' && (
                <CarAddressSection />
            )}

            {selectedDeliveryMethod?.method === 'deliveryCourier' && (
                <AddressSection />
            )}

            {selectedDeliveryMethod?.method === 'dineIn' && (
                <TableSection
                    tableNumber={tableNumber}
                    onIncrement={incrementTableNumber}
                    onDecrement={decrementTableNumber}
                />
            )}

            <PaymentSection
                paymentType={paymentType}
                onPaymentTypeChange={changePaymentType}
            />

            <CouponSection
                couponType={couponType}
                couponCode={couponCode}
                couponCodeError={couponCodeError}
                onCouponTypeChange={changeCouponType}
                onCouponCodeChange={changeCouponCode}
            />

            <SummarySection
                cartModal={cartModal}
                onToggleCartModal={toggleCartModal}
                deliveryType={deliveryType}
            />
        </div>
    );
}

export default OrderDetailInex
