import style from './cart.module.css';

import React, { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { Button, Checkbox, Spinner, Tooltip } from '@chakra-ui/react';
import { toast } from 'react-hot-toast';
import { useRouter } from 'next/router';
import { getAuth } from '~/libs/auth';
import { useCartStore } from '~/modules/cart/stores/useCartStore';

import CartItemModule from '~/modules/cart/components/Item';
import CartSummary from '~/modules/cart/components/Summary';
import clsxm from '~/libs/clsxm';
import useDevice from '@/core/hooks/useDevice';
import CartSummaryMobile from '~/modules/cart/components/CartSummaryMobile';
import Image from '~/components/ui/image';
import { CartItem } from '~/types/cart';
import { deleteUserCart, upsertUserCart } from '~/services/cart';
import { Trash2Icon } from 'lucide-react';
import { useProductCartContext } from '@/contexts/ProductCartContext';

const CartPage = () => {
  const router = useRouter();
  const auth = getAuth();
  const [isStepApproval, setIsStepApproval] = useState(false);
  const [isSelectedAll, setIsSelectedAll] = useState(false);
  const [isButtonChek, setIsButtonChek] = useState(false);
  const [buttonSelectNow, setButtonSelectNow] = useState(true);
  const [isLoad, setIsLoad] = useState<boolean>(false);
  const [isLoadDelete, setIsLoadDelete] = useState<boolean>(false);
  const { loadCart, cart, summary, updateCartItem } = useCartStore();
  const useDivvice = useDevice();
  const { setRefreshCart } = useProductCartContext();
  const [isTop, setIsTop] = useState(true);
  const [hasChanged, setHasChanged] = useState(false);
  const prevCartRef = useRef<CartItem[] | null>(null);

  useEffect(() => {
    const handleScroll = () => {
      setIsTop(window.scrollY < 200);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  useEffect(() => {
    if (typeof auth === 'object' && !cart) {
      loadCart(auth.id);
      setIsStepApproval(auth?.feature?.soApproval);
    }
  }, [auth, loadCart, cart, isButtonChek]);

  useEffect(() => {
    if (typeof auth === 'object' && !cart) {
      loadCart(auth.id);
      setIsStepApproval(auth?.feature?.soApproval);
    }
  }, [auth, loadCart, cart, isButtonChek]);

  useEffect(() => {
    const hasSelectedChanged = () => {
      if (prevCartRef.current && cart) {
        const prevCart = prevCartRef.current;
        return cart.products.some(
          (item, index) =>
            prevCart[index] && prevCart[index].selected !== item.selected
        );
      }
      return false;
    };

    if (hasSelectedChanged()) {
      setHasChanged(true);
      // Perform necessary actions here if selection has changed
    } else {
      setHasChanged(false);
    }

    prevCartRef.current = cart ? [...cart.products] : null;
  }, [cart]);

  const hasSelectedPromo = useMemo(() => {
    if (!cart) return false;
    return cart?.products?.some(
      (item) => item.cart_type === 'promotion' && item.selected
    );
  }, [cart]);

  const hasSelected = useMemo(() => {
    if (!cart) return false;
    return cart?.products?.some((item) => item.selected);
  }, [cart]);

  const hasSelectNoPrice = useMemo(() => {
    if (!cart) return false;
    return cart?.products?.some(
      (item) => item.selected && item.price.price_discount === 0
    );
  }, [cart]);

  const hasSelectedAll = useMemo(() => {
    if (!cart || !Array.isArray(cart.products)) return false;
    return cart.products.every((item) => item.selected);
  }, [cart]);

  useEffect(() => {
    const updateCartItems = async () => {
      if (typeof auth === 'object' && cart) {
        const upsertPromises = cart.products.map((item) =>
          upsertUserCart({
            userId: auth.id,
            type: item.cart_type,
            id: item.id,
            qty: item.quantity,
            selected: item.selected,
          })
        );
        try {
          await Promise.all(upsertPromises);
          await loadCart(auth.id);
        } catch (error) {
          console.error('Failed to update cart items:', error);
        }
      }
    };

    updateCartItems();
  }, [hasChanged]);

  const handleCheckout = () => {
    router.push('/shop/checkout');
  };

  const handleQuotation = () => {
    if (hasSelectedPromo || !hasSelected) {
      toast.error('Maaf, Barang promo tidak dapat dibuat quotation');
    } else {
      router.push('/shop/quotation');
    }
  };

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (cart) {
      const updatedCart = {
        ...cart,
        products: cart.products.map((item) => ({
          ...item,
          selected: !hasSelectedAll,
        })),
      };

      updateCartItem(updatedCart);
      if (hasSelectedAll) {
        setIsSelectedAll(false);
      } else {
        setIsSelectedAll(true);
      }
    }
  };

  const handleDelete = async () => {
    if (typeof auth !== 'object' || !cart) return;

    setIsLoadDelete(true);
    for (const item of cart.products) {
      if (item.selected === true) {
        await deleteUserCart(auth.id, [item.cart_id]);
        await loadCart(auth.id);
      }
    }
    setIsLoadDelete(false);
    setRefreshCart(true);
  };

  return (
    <>
      <div
        className={`${
          isTop ? 'border-b-[0px]' : 'border-b-[1px]'
        } sticky  md:top-[157px] flex-col  bg-white py-4 border-gray-300 z-50 sm:w-full md:w-3/4`}
      >
        <h1 className={`${style['title']}`}>Keranjang Belanja</h1>
        <div className='h-2' />
        <div className={`flex items-center object-center justify-between `}>
          <div className='flex items-center object-center'>
            {isLoad && <Spinner className='my-auto' size='sm' />}
            {!isLoad && (
              <Checkbox
                borderColor='gray.600'
                colorScheme='red'
                size='lg'
                isChecked={hasSelectedAll}
                onChange={handleChange}
              />
            )}
            <p className='p-2 text-caption-2'>
              {hasSelectedAll ? 'Uncheck all' : 'Select all'}
            </p>
          </div>
          <div className='delate all flex items-center object-center'>
            <Tooltip
              label={clsxm({
                'Tidak ada item yang dipilih': !hasSelected,
              })}
            >
              <Button
                bg='#fadede'
                variant='outline'
                colorScheme='red'
                w='full'
                isDisabled={!hasSelected}
                onClick={handleDelete}
              >
                {isLoadDelete && <Spinner size='xs' />}
                {!isLoadDelete && <Trash2Icon size={16} />}
                <p className='text-sm ml-2'>Hapus Barang</p>
              </Button>
            </Tooltip>
          </div>
        </div>
      </div>

      <div className={style['content']}>
        <div className={style['item-wrapper']}>
          <div className={style['item-skeleton']}>
            {!cart && <CartItemModule.Skeleton count={5} height='120px' />}
          </div>

          <div className={style['items']}>
            {cart?.products?.map((item) => (
              <CartItemModule key={item.id} item={item} />
            ))}

            {cart?.products?.length === 0 && (
              <div className='flex flex-col items-center'>
                <Image
                  src='/images/empty_cart.svg'
                  alt='Empty Cart'
                  width={450}
                  height={450}
                />
                <div className='text-title-sm md:text-title-lg text-center font-semibold'>
                  Keranjangnya masih kosong nih
                </div>
                <div className='text-body-2 md:text-body-1 text-center mt-3'>
                  Yuk, tambahin barang-barang yang kamu mau ke keranjang
                  sekarang!
                  <br />
                  Ada banyak potongan belanjanya pakai kode voucher
                </div>
                <Link
                  href='/'
                  className='btn-solid-red rounded-full text-body-1 mt-6'
                >
                  Mulai Belanja
                </Link>
              </div>
            )}
          </div>
        </div>
        <div
          className={`${style['summary-wrapper']} ${
            useDivvice.isMobile && cart?.product_total === 0 ? 'hidden' : ''
          }`}
        >
          <div className={style['summary']}>
            {useDivvice.isMobile && (
              <CartSummaryMobile {...summary} isLoaded={!!cart} />
            )}
            {!useDivvice.isMobile && (
              <CartSummary {...summary} isLoaded={!!cart} />
            )}

            <div
              className={
                isStepApproval
                  ? style['summary-buttons-step-approval']
                  : style['summary-buttons']
              }
            >
              <Tooltip
                label={
                  hasSelectedPromo &&
                  'Barang promo tidak dapat dibuat quotation'
                }
              >
                <Button
                  colorScheme='yellow'
                  w='full'
                  isDisabled={hasSelectedPromo || !hasSelected}
                  onClick={handleQuotation}
                >
                  Quotation
                </Button>
              </Tooltip>
              {!isStepApproval && (
                <Tooltip
                  label={clsxm({
                    'Tidak ada item yang dipilih': !hasSelected,
                    'Terdapat item yang tidak ada harga': hasSelectNoPrice,
                  })}
                >
                  <Button
                    colorScheme='red'
                    w='full'
                    isDisabled={!hasSelected || hasSelectNoPrice}
                    onClick={handleCheckout}
                  >
                    Checkout
                  </Button>
                </Tooltip>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default CartPage;
