'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations, useLocale } from 'next-intl'
import { AnimatePresence } from 'framer-motion'
import Container from '@/components/frontend/Container'
import CartItem from '@/components/frontend/cart/CartItem'
import CartSummary from '@/components/frontend/cart/CartSummary'
import CartEmpty from '@/components/frontend/cart/CartEmpty'
import { useCartStore } from '@/store/cartStore'
import { useCurrencyStore } from '@/store/currencyStore'
import { useCheckoutSettingsStore } from '@/store/checkoutSettingsStore'
import { computeItemCouponDiscounts } from '@/lib/cart/itemCouponDiscount'

export default function CartPageClient() {
  const router = useRouter()
  const locale = useLocale()
  const t = useTranslations('Cart')
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const {
    items,
    couponCode,
    couponDiscount,
    appliedCoupon,
    loading,
    fetchCart,
    updateQuantity,
    removeItem,
    applyCoupon,
    removeCoupon,
    getSubtotal,
  } = useCartStore()
  const { minOrderAmount, vatLabel, vatPercentage, calculateDeliveryFee, calculateTax } = useCheckoutSettingsStore()

  // `loading` starts false, so without this the page first renders the empty-cart
  // state, then the loading text, then the items — three different heights,
  // which pushed the footer around (Lighthouse CLS 0.84). Stay in one stable,
  // full-height loading state until the first fetch has actually finished.
  const [ready, setReady] = useState(false)

  useEffect(() => {
    fetchCart(locale).finally(() => setReady(true))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale])

  const subtotal = getSubtotal()
  const deliveryFee = items.length === 0 ? 0 : calculateDeliveryFee(subtotal)
  const tax = items.length === 0 ? 0 : calculateTax(subtotal)
  const total = Math.max(subtotal + deliveryFee + tax - couponDiscount, 0)
  const hasOutOfStockItem = items.some((item) => !item.in_stock)
  const belowMinOrder = minOrderAmount > 0 && subtotal < minOrderAmount
  const itemDiscounts = computeItemCouponDiscounts(items, couponDiscount)

  const handleProceedToCheckout = () => {
    router.push('/checkout')
  }

  if (!ready || (loading && items.length === 0)) {
    return (
      <Container className="py-12 min-h-[60vh]">
        <p className="text-center text-gray-custom">{t('loading')}</p>
      </Container>
    )
  }

  if (items.length === 0) {
    return (
      <Container className="py-12 min-h-[60vh]">
        <CartEmpty />
      </Container>
    )
  }

  return (
    <Container className="py-8">
      <h1 className="text-2xl font-bold text-dark mb-6">{t('itemsCount', { count: items.length })}</h1>

      <div className="flex flex-col lg:flex-row gap-8">
        {/* Cart Items */}
        <div className="flex-1">
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="hidden sm:grid grid-cols-12 gap-4 pb-3 border-b border-gray-100 text-sm text-gray-custom">
              <div className="col-span-6">{t('product')}</div>
              <div className="col-span-2 text-center">{t('quantity')}</div>
              <div className="col-span-2 text-right">{t('price')}</div>
              <div className="col-span-2 text-right">{t('total')}</div>
            </div>

            <AnimatePresence mode="popLayout">
              {items.map((item) => (
                <CartItem
                  key={item.id}
                  id={item.id}
                  name={item.product_name}
                  variantName={item.variant_name}
                  price={item.unit_price}
                  quantity={item.quantity}
                  imageUrl={item.image_url}
                  slug={item.slug}
                  inStock={item.in_stock}
                  couponEligible={appliedCoupon && !appliedCoupon.appliesToAll ? item.coupon_eligible : null}
                  itemDiscount={itemDiscounts.get(item.id) ?? 0}
                  onUpdateQuantity={updateQuantity}
                  onRemove={removeItem}
                />
              ))}
            </AnimatePresence>
          </div>
        </div>

        {/* Cart Summary */}
        <div className="lg:w-96">
          <CartSummary
            subtotal={subtotal}
            deliveryFee={deliveryFee}
            tax={tax}
            vatLabel={vatLabel}
            vatPercentage={vatPercentage}
            discount={couponDiscount}
            total={total}
            appliedCouponCode={couponCode}
            appliedCoupon={appliedCoupon}
            onApplyCoupon={applyCoupon}
            onRemoveCoupon={removeCoupon}
            onProceedToCheckout={handleProceedToCheckout}
            isCheckoutDisabled={hasOutOfStockItem || belowMinOrder}
            blockedReason={
              hasOutOfStockItem
                ? t('outOfStockBlocked')
                : belowMinOrder
                  ? t('minOrderNotMet', { amount: formatAmount(minOrderAmount) })
                  : undefined
            }
          />
        </div>
      </div>
    </Container>
  )
}
