'use client';

import React from 'react';
import Link from 'next/link';
import { useParams, useRouter, usePathname } from 'next/navigation';
import Button from '@/components/button/PrimaryButton';
import { useGetProducts } from '@/app/[name]/(Main)/hooks/useMenuData';
import type { Product } from '@/app/[name]/(Main)/types/Types';
import { useCart } from '../hook/useCart';
import { useTranslation } from 'react-i18next';
import { useGetProfile } from '@/app/[name]/(Profile)/profile/hooks/userProfileData';
import { useGetCartItems } from '../hooks/useCartData';
import { useCartStore } from '../store/Store';

interface CartSummaryProps {
  isPremium: boolean;
}

const CartSummary = ({ isPremium }: CartSummaryProps) => {
  const params = useParams();
  const router = useRouter();
  const pathname = usePathname();
  const name = params.name as string;
  const { isSuccess } = useGetProfile();
  const { data: productsResponse } = useGetProducts();
  const products = React.useMemo(
    () => productsResponse?.data ?? [],
    [productsResponse?.data]
  );
  const { items } = useCart();
  const { data: cartData } = useGetCartItems(isSuccess);
  const { t } = useTranslation("parallels", { keyPrefix: "Cart" });
  const { description, setDescription } = useCartStore();

  const cartEntries = React.useMemo(() => {
    if (products.length === 0) return [];

    const result: { product: Product; variantId: string; quantity: number }[] =
      [];

    Object.entries(items)
      .filter(([, detail]) => detail?.quantity && detail.quantity > 0)
      .forEach(([variantId, detail]) => {
        const product = products.find((productItem) =>
          productItem.variants?.some(
            (variant) => String(variant.id) === String(variantId)
          )
        );

        if (!product) return;

        result.push({
          product,
          variantId: String(variantId),
          quantity: detail.quantity,
        });
      });

    return result;
  }, [products, items]);

  const totalPrice = React.useMemo(() => {
    // اگر داده از API آمده و total وجود دارد، از آن استفاده می‌کنیم
    if (isSuccess && cartData?.data?.total !== undefined) {
      return cartData.data.total;
    }

    // در غیر این صورت، محاسبه محلی با در نظر گرفتن تخفیف و تنوع‌ها
    return cartEntries.reduce((sum, entry) => {
      const variant = entry.product.variants?.find(
        (v) => String(v.id) === entry.variantId
      );
      const basePrice = variant?.price ?? entry.product.price ?? 0;
      const discount = entry.product.discount ?? 0;
      const priceAfterDiscount = basePrice * (1 - discount / 100);
      return sum + priceAfterDiscount * entry.quantity;
    }, 0);
  }, [cartEntries, isSuccess, cartData?.data?.total]);

  const isCartEmpty = cartEntries.length === 0;

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

  return (
    <>
      {!isCartEmpty && (
        <>
          {isPremium && (
            <div className='mt-2 mb-4'>
              <div className='relative'>
                <h3 className='text-sm'>{t('InputDescription.Label')}</h3>
                <textarea
                  className='w-full px-4 py-2.5 mt-4 text-sm2 leading-6 outline-0 border border-border rounded-normal resize-none focus:ring-0'
                  placeholder={t('InputDescription.Placeholder')}
                  id='description'
                  name='description'
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                ></textarea>
                <span className='absolute top-4 right-2 px-2 bg-background text-foreground text-xs'></span>
              </div>
            </div>
          )}

          <div className='fixed bottom-0 left-0 right-0 z-50 bg-white dark:bg-container 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-disabled-text'>{t('PayableAmountLabel')}</div>
                {
                  isPremium &&
                  <div className='text-sm mt-2 font-semibold dark:text-foreground'>{formatPrice(totalPrice)} تومان</div>

                }
              </div>

              {isPremium && (
                <Link
                  href={`/${name}/order/checkout/0`}
                  onClick={(event) => {
                    if (!isSuccess) {
                      event.preventDefault();
                      const redirectUrl = encodeURIComponent(pathname);
                      router.replace(`/${name}/auth?redirect=${redirectUrl}`);
                      return;
                    }
                  }}
                >
                  <Button className='w-fit! px-10 dark:bg-white dark:text-black! dark:hover:bg-gray-100'>
                    {t('ButtonCheckout')}
                  </Button>
                </Link>
              )}
              {!isPremium && (
                <div className='text-sm mt-2 font-semibold dark:text-foreground'>{formatPrice(totalPrice)} تومان</div>
              )}
            </div>
          </div>
        </>
      )}

      {/* {!isCartEmpty && (
        <div className='flex items-center justify-between rounded-xl border border-border px-4 py-3 text-xs text-muted-foreground'>
          <span>{t('CartControlsHint', { defaultValue: 'برای ویرایش تعداد، از دکمه‌های هر آیتم استفاده کنید.' })}</span>
          <div className='flex items-center gap-1 text-foreground'>
            <Add size={16} />
            <Minus size={16} />
          </div>
        </div>
      )} */}
    </>
  );
};

export default CartSummary;

