'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useCart } from '@/context/CartContext';
import { useWishlist } from '@/context/WishlistContext';
import { useCompare } from '@/context/CompareContext';
import { useLanguage } from '@/context/LanguageContext';
import type { Product } from '@/lib/data/products';
import styles from './ProductCard.module.css';

interface Props {
  product: Product;
}

export default function ProductCard({ product }: Props) {
  const { addItem } = useCart();
  const { toggle, isWishlisted } = useWishlist();
  const { addProduct, isComparing } = useCompare();
  const { t, language } = useLanguage();
  const [added, setAdded] = useState(false);

  const name = language === 'ar' ? product.nameAr : product.name;
  const wishlisted = isWishlisted(product.id);
  const comparing = isComparing(product.id);

  const handleAddToCart = (e: React.MouseEvent) => {
    e.preventDefault();
    addItem({
      id: product.id,
      name: product.name,
      nameAr: product.nameAr,
      price: product.price,
      image: product.image,
      slug: product.slug,
    });
    setAdded(true);
    setTimeout(() => setAdded(false), 1500);
  };

  const handleWishlist = (e: React.MouseEvent) => {
    e.preventDefault();
    toggle({
      id: product.id,
      name: product.name,
      nameAr: product.nameAr,
      price: product.price,
      image: product.image,
      slug: product.slug,
      originalPrice: product.originalPrice,
    });
  };

  const handleCompare = (e: React.MouseEvent) => {
    e.preventDefault();
    addProduct({
      id: product.id,
      name: product.name,
      nameAr: product.nameAr,
      price: product.price,
      image: product.image,
      slug: product.slug,
      specs: product.specs,
    });
  };

  return (
    <Link href={`/products/${product.slug}`} className={styles.card}>
      {/* Image */}
      <div className={styles.imageWrap}>
        <div className={styles.imagePlaceholder}>
          <span style={{ fontSize: '4rem' }}>
            {product.category === 'smartphones' ? '📱' :
             product.category === 'tablets' ? '💻' :
             product.category === 'watches' ? '⌚' :
             product.category === 'gaming' ? '🎮' : '🎧'}
          </span>
        </div>

        {/* Action Buttons */}
        <div className={styles.actions}>
          <button
            className={`${styles.actionBtn} ${wishlisted ? styles.active : ''}`}
            onClick={handleWishlist}
            title={t.product.addToWishlist}
          >
            {wishlisted ? '❤️' : '🤍'}
          </button>
          <button
            className={`${styles.actionBtn} ${comparing ? styles.active : ''}`}
            onClick={handleCompare}
            title={t.product.compare}
          >
            ⚖️
          </button>
        </div>

        {/* Badges */}
        <div className={styles.badges}>
          {product.discount && (
            <span className="badge badge-orange">-{product.discount}%</span>
          )}
          {product.isNew && (
            <span className="badge badge-blue">{language === 'ar' ? 'جديد' : 'NEW'}</span>
          )}
          {product.isFlashDeal && (
            <span className="badge" style={{ background: 'rgba(255,215,0,0.15)', color: '#FFD700', border: '1px solid rgba(255,215,0,0.3)' }}>
              ⚡ {language === 'ar' ? 'عرض' : 'DEAL'}
            </span>
          )}
        </div>
      </div>

      {/* Body */}
      <div className={styles.body}>
        <div className={styles.brand}>{product.brand}</div>
        <div className={styles.name}>{name}</div>

        {/* Rating */}
        <div className={styles.rating}>
          <span style={{ color: '#FFD700' }}>{'★'.repeat(Math.round(product.rating))}</span>
          <span className={styles.ratingCount}>({product.reviewCount})</span>
        </div>

        {/* Price */}
        <div className={styles.price}>
          <span className={styles.current}>{product.price.toFixed(3)} {t.product.kwd}</span>
          {product.originalPrice && (
            <span className={styles.original}>{product.originalPrice.toFixed(3)}</span>
          )}
        </div>

        {/* Stock */}
        <div className={`${styles.stock} ${!product.inStock ? styles.outOfStock : ''}`}>
          {product.inStock ? `✓ ${t.product.inStock}` : `✗ ${t.product.outOfStock}`}
        </div>
      </div>

      {/* Footer */}
      <div className={styles.footer} onClick={e => e.preventDefault()}>
        <div style={{ display: 'flex', gap: '8px', width: '100%' }}>
          <button
            className={`btn ${added ? 'btn-orange' : 'btn-outline'} btn-sm`}
            style={{ flex: 1, padding: '8px 0' }}
            onClick={handleAddToCart}
            disabled={!product.inStock || added}
            title={t.product.addToCart}
          >
            {added ? '✓' : '🛒'}
          </button>
          <button
            className="btn btn-primary btn-sm"
            style={{ flex: 3, padding: '8px 0' }}
            onClick={(e) => { handleAddToCart(e); window.location.href = '/checkout'; }}
            disabled={!product.inStock}
          >
            ⚡ {language === 'ar' ? 'شراء سريع' : 'Quick Buy'}
          </button>
        </div>
      </div>
    </Link>
  );
}
