'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  getCart,
  removeFromCart,
  updateCartQuantity,
  clearCart,
  CartItem,
} from '@/lib/cart';
import { useI18n } from '@/lib/i18n/context';

export default function CartPage() {
  const router = useRouter();
  const { t, isRtl, locale } = useI18n();
  const numberLocale = locale === 'ar' ? 'ar-SA' : 'en-US';
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setCartItems(getCart());
    setMounted(true);
  }, []);

  const updateQty = (productId: number, qty: number) => {
    if (qty < 1) return;
    const updated = updateCartQuantity(productId, qty);
    setCartItems(updated);
  };

  const removeItem = (productId: number) => {
    const updated = removeFromCart(productId);
    setCartItems(updated);
  };

  const getTotalPrice = () =>
    cartItems.reduce((sum, i) => sum + i.unit_price * i.quantity, 0);

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

  const backIcon = isRtl ? 'ri-arrow-right-line' : 'ri-arrow-left-line';

  if (!mounted) return null;

  return (
    <div
      dir={isRtl ? 'rtl' : 'ltr'}
      className="flex flex-col flex-1 bg-gradient-to-br from-blue-50 via-white to-gray-50"
    >
      <main className="max-w-5xl mx-auto px-6 py-12 flex-1 w-full">
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-2">
            <button
              type="button"
              onClick={() => router.push('/store')}
              className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
            >
              <i className={`${backIcon} text-xl text-gray-700`}></i>
            </button>
            <h1 className="text-3xl font-bold text-gray-900">{t('cart.title')}</h1>
          </div>
          <p className={`text-gray-600 ${isRtl ? 'mr-13' : 'ml-13'}`}>
            {t('cart.itemsCount', { count: String(cartItems.length) })}
          </p>
        </div>

        {cartItems.length === 0 ? (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
            <i className="ri-shopping-cart-line text-6xl text-gray-300 mb-4 block"></i>
            <h2 className="text-xl font-bold text-gray-900 mb-2">{t('cart.emptyTitle')}</h2>
            <p className="text-gray-600 mb-6">{t('cart.emptySubtitle')}</p>
            <Link
              href="/store"
              className="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer whitespace-nowrap"
            >
              {t('cart.browseStore')}
            </Link>
          </div>
        ) : (
          <>
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mb-6">
              {cartItems.map((item, index) => (
                <div
                  key={item.product_id}
                  className={`p-6 flex items-center gap-6 ${index !== cartItems.length - 1 ? 'border-b border-gray-100' : ''}`}
                >
                  <div className="w-24 h-24 bg-gray-100 rounded-lg overflow-hidden flex items-center justify-center flex-shrink-0">
                    {item.image ? (
                      <img src={item.image} alt={item.product_name} className="w-full h-full object-cover" />
                    ) : (
                      <i className="ri-image-line text-3xl text-gray-300"></i>
                    )}
                  </div>

                  <div className="flex-1">
                    <h3 className="text-lg font-bold text-gray-900 mb-2">{item.product_name}</h3>
                    <p className="text-blue-600 font-semibold">
                      {item.unit_price.toLocaleString(numberLocale)} {t('common.sar')}
                      <span className={`text-gray-500 text-sm ${isRtl ? 'mr-2' : 'ml-2'}`}>{t('cart.perUnit')}</span>
                    </p>
                  </div>

                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => updateQty(item.product_id, item.quantity - 1)}
                      className="w-10 h-10 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors cursor-pointer"
                    >
                      <i className="ri-subtract-line text-xl text-gray-700"></i>
                    </button>
                    <input
                      type="number"
                      value={item.quantity}
                      onChange={(e) => updateQty(item.product_id, parseInt(e.target.value, 10) || 1)}
                      className="w-16 h-10 text-center border border-gray-200 rounded-lg font-semibold text-gray-900"
                      min="1"
                    />
                    <button
                      type="button"
                      onClick={() => updateQty(item.product_id, item.quantity + 1)}
                      className="w-10 h-10 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors cursor-pointer"
                    >
                      <i className="ri-add-line text-xl text-gray-700"></i>
                    </button>
                  </div>

                  <div className={`min-w-[120px] ${isRtl ? 'text-left' : 'text-right'}`}>
                    <p className="text-xl font-bold text-gray-900">
                      {(item.unit_price * item.quantity).toLocaleString(numberLocale)} {t('common.sar')}
                    </p>
                  </div>

                  <button
                    type="button"
                    onClick={() => removeItem(item.product_id)}
                    className="w-10 h-10 flex items-center justify-center text-red-600 hover:bg-red-50 rounded-lg transition-colors cursor-pointer"
                  >
                    <i className="ri-delete-bin-line text-xl"></i>
                  </button>
                </div>
              ))}
            </div>

            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <div className="flex items-center justify-between mb-6">
                <span className="text-lg font-semibold text-gray-700">{t('cart.total')}</span>
                <span className="text-3xl font-bold text-blue-600">
                  {getTotalPrice().toLocaleString(numberLocale)} {t('common.sar')}
                </span>
              </div>
              <div className="flex gap-3 flex-wrap">
                <button
                  type="button"
                  onClick={handleCheckout}
                  className="flex-1 min-w-[200px] bg-blue-600 text-white py-4 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer whitespace-nowrap text-lg font-semibold"
                >
                  {t('cart.checkout')}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    clearCart();
                    setCartItems([]);
                  }}
                  className="px-6 py-4 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors cursor-pointer font-semibold"
                >
                  {t('cart.clearCart')}
                </button>
              </div>
            </div>
          </>
        )}
      </main>
    </div>
  );
}
