'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import StoreLayout from '@/components/layout/StoreLayout';
import { useCart } from '@/context/CartContext';
import { useLanguage } from '@/context/LanguageContext';
import styles from './cart.module.css';

export default function CartPage() {
  const { items, removeItem, updateQuantity, total, coupon, couponDiscount, applyCoupon, removeCoupon } = useCart();
  const { t, language } = useLanguage();
  const router = useRouter();
  const [couponInput, setCouponInput] = useState('');
  const [couponMsg, setCouponMsg] = useState('');

  const subtotal = items.reduce((s, i) => s + i.price * i.quantity, 0);
  const shipping = total > 15 ? 0 : 1.5;
  const discountAmt = (subtotal * couponDiscount) / 100;
  const finalTotal = total + shipping;

  const handleApplyCoupon = () => {
    const ok = applyCoupon(couponInput);
    setCouponMsg(ok
      ? (language === 'ar' ? `✓ تم تطبيق الخصم ${couponDiscount}%` : `✓ ${couponDiscount}% discount applied!`)
      : (language === 'ar' ? '✗ كود خاطئ' : '✗ Invalid coupon code'));
    setTimeout(() => setCouponMsg(''), 3000);
  };

  if (items.length === 0) return (
    <StoreLayout>
      <div className={styles.empty}>
        <div className={styles.emptyIcon}>🛒</div>
        <h2>{t.cart.empty}</h2>
        <p>{t.cart.emptySubtitle}</p>
        <Link href="/products" className="btn btn-primary btn-lg">{t.cart.continueShopping}</Link>
      </div>
    </StoreLayout>
  );

  return (
    <StoreLayout>
      <div className={styles.page}>
        <div className="container">
          <h1 className={styles.title}>{t.cart.title}</h1>
          <div className={styles.layout}>
            {/* Items */}
            <div className={styles.items}>
              {items.map(item => (
                <div key={item.id} className={styles.item}>
                  <div className={styles.itemImg}>
                    <span style={{ fontSize: '2.5rem' }}>📱</span>
                  </div>
                  <div className={styles.itemInfo}>
                    <div className={styles.itemName}>{language === 'ar' ? item.nameAr : item.name}</div>
                    <div className={styles.itemPrice}>{item.price.toFixed(3)} {t.product.kwd}</div>
                  </div>
                  <div className={styles.qtyControl}>
                    <button onClick={() => updateQuantity(item.id, item.quantity - 1)}>−</button>
                    <span>{item.quantity}</span>
                    <button onClick={() => updateQuantity(item.id, item.quantity + 1)}>+</button>
                  </div>
                  <div className={styles.itemTotal}>
                    {(item.price * item.quantity).toFixed(3)} {t.product.kwd}
                  </div>
                  <button className={styles.removeBtn} onClick={() => removeItem(item.id)}>🗑️</button>
                </div>
              ))}

              {/* Coupon */}
              <div className={styles.couponRow}>
                <input
                  className="form-input"
                  placeholder={t.cart.coupon}
                  value={couponInput}
                  onChange={e => setCouponInput(e.target.value)}
                  style={{ maxWidth: '260px' }}
                />
                <button className="btn btn-outline" onClick={handleApplyCoupon}>{t.cart.applyCoupon}</button>
                {coupon && <button className="btn btn-ghost btn-sm" onClick={removeCoupon}>✕ {coupon}</button>}
              </div>
              {couponMsg && <div className={styles.couponMsg} style={{ color: couponMsg.includes('✓') ? 'var(--success)' : 'var(--error)' }}>{couponMsg}</div>}

              {/* Free shipping message */}
              {shipping === 0 ? (
                <div className={styles.freeShip}>✓ {t.cart.freeShipping}</div>
              ) : (
                <div className={styles.freeShipHint}>
                  {(t.cart.freeShippingThreshold as string).replace('{amount}', (15 - total).toFixed(3))}
                </div>
              )}
            </div>

            {/* Summary */}
            <div className={styles.summary}>
              <h3 className={styles.summaryTitle}>{language === 'ar' ? 'ملخص الطلب' : 'Order Summary'}</h3>
              <div className={styles.summaryRows}>
                <div className={styles.summaryRow}><span>{t.cart.subtotal}</span><span>{subtotal.toFixed(3)} {t.product.kwd}</span></div>
                {couponDiscount > 0 && <div className={styles.summaryRow} style={{ color: 'var(--success)' }}><span>{t.cart.discount} ({couponDiscount}%)</span><span>−{discountAmt.toFixed(3)} {t.product.kwd}</span></div>}
                <div className={styles.summaryRow}><span>{t.cart.shipping}</span><span>{shipping === 0 ? (language === 'ar' ? 'مجاني' : 'FREE') : `${shipping.toFixed(3)} ${t.product.kwd}`}</span></div>
              </div>
              <div className={styles.summaryTotal}>
                <span>{t.cart.total}</span>
                <span>{finalTotal.toFixed(3)} {t.product.kwd}</span>
              </div>
              <button className="btn btn-primary btn-full btn-lg" onClick={() => router.push('/checkout')}>
                {t.cart.checkout}
              </button>
              <Link href="/products" className="btn btn-ghost btn-full" style={{ marginTop: '8px', justifyContent: 'center' }}>
                ← {t.cart.continueShopping}
              </Link>
            </div>
          </div>
        </div>
      </div>
    </StoreLayout>
  );
}
