'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import StoreLayout from '@/components/layout/StoreLayout';
import ProductCard from '@/components/ui/ProductCard';
import { useCart } from '@/context/CartContext';
import { useWishlist } from '@/context/WishlistContext';
import { useCompare } from '@/context/CompareContext';
import { useLanguage } from '@/context/LanguageContext';
import { useAuth } from '@/context/AuthContext';
import { products } from '@/lib/data/products';
import styles from './product.module.css';

interface Props {
  params: { slug: string };
}

export default function ProductDetailPage({ params }: Props) {
  const { t, language } = useLanguage();
  const { addItem } = useCart();
  const { toggle, isWishlisted } = useWishlist();
  const { addProduct, isComparing } = useCompare();
  const [activeTab, setActiveTab] = useState<'specs' | 'reviews'>('specs');
  const [qty, setQty] = useState(1);
  const [toast, setToast] = useState('');
  
  const product = products.find(p => p.slug === params.slug);
  const { user } = useAuth();
  
  const [selectedColor, setSelectedColor] = useState(product?.specs?.colors?.[0] || '');
  const [selectedStorage, setSelectedStorage] = useState(product?.specs?.storage || '');
  
  const [reviews, setReviews] = useState<any[]>([]);
  const [reviewForm, setReviewForm] = useState({ rating: 5, comment: '' });
  const [submittingReview, setSubmittingReview] = useState(false);

  React.useEffect(() => {
    if (product) {
      fetch(`/api/reviews?productId=${product.id}`)
        .then(res => res.json())
        .then(data => {
          if (data.success) setReviews(data.reviews);
        })
        .catch(console.error);
    }
  }, [product?.id]);
  const related = products.filter(p => p.category === product?.category && p.id !== product?.id).slice(0, 4);

  if (!product) return (
    <StoreLayout>
      <div style={{ padding: '100px 24px', textAlign: 'center' }}>
        <div style={{ fontSize: '3rem', marginBottom: '16px' }}>📱</div>
        <h2 style={{ color: 'var(--text-primary)', marginBottom: '12px' }}>Product not found</h2>
        <Link href="/products" className="btn btn-primary">Browse Products</Link>
      </div>
    </StoreLayout>
  );

  const name = language === 'ar' ? product.nameAr : product.name;
  const desc = language === 'ar' ? product.descriptionAr : product.description;

  const showToast = (msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(''), 2500);
  };

  const handleAddToCart = () => {
    for (let i = 0; i < qty; i++) {
      addItem({ id: product.id, name: product.name, nameAr: product.nameAr, price: product.price, image: product.image, slug: product.slug });
    }
    showToast(t.productDetail.addedToCart);
  };

  const handleWishlist = () => {
    toggle({ id: product.id, name: product.name, nameAr: product.nameAr, price: product.price, image: product.image, slug: product.slug, originalPrice: product.originalPrice });
    showToast(t.productDetail.addedToWishlist);
  };

  const handleCompare = () => {
    addProduct({ id: product.id, name: product.name, nameAr: product.nameAr, price: product.price, image: product.image, slug: product.slug, specs: product.specs });
    showToast(t.productDetail.addedToCompare);
  };

  const submitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user) {
      showToast('Please login to submit a review');
      return;
    }
    setSubmittingReview(true);
    try {
      const res = await fetch('/api/reviews', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          productId: product.id,
          userId: user.id,
          userName: user.name,
          rating: reviewForm.rating,
          comment: reviewForm.comment
        })
      });
      const data = await res.json();
      if (data.success) {
        setReviews([data.review, ...reviews]);
        setReviewForm({ rating: 5, comment: '' });
        showToast('Review submitted successfully!');
      } else {
        showToast(data.message || 'Error submitting review');
      }
    } catch (err: any) {
      showToast('Error submitting review');
    } finally {
      setSubmittingReview(false);
    }
  };

  const specRows: [string, string][] = [
    [language === 'ar' ? 'الشاشة' : 'Display', product.specs.display],
    [language === 'ar' ? 'المعالج' : 'Processor', product.specs.processor],
    [language === 'ar' ? 'الذاكرة العشوائية' : 'RAM', product.specs.ram],
    [language === 'ar' ? 'التخزين' : 'Storage', product.specs.storage],
    [language === 'ar' ? 'البطارية' : 'Battery', product.specs.battery],
    [language === 'ar' ? 'الكاميرا' : 'Camera', product.specs.camera],
    [language === 'ar' ? 'نظام التشغيل' : 'OS', product.specs.os],
    product.specs.network ? [language === 'ar' ? 'الشبكة' : 'Network', product.specs.network as string] : null,
    product.specs.weight ? [language === 'ar' ? 'الوزن' : 'Weight', product.specs.weight as string] : null,
  ].filter(Boolean) as [string, string][];

  return (
    <StoreLayout>
      {toast && <div className="toast">✓ {toast}</div>}
      <div className={styles.page}>
        <div className="container">
          {/* Breadcrumb */}
          <div className="breadcrumb" style={{ marginBottom: '24px' }}>
            <Link href="/">{t.nav.home}</Link>
            <span className="breadcrumb-sep">›</span>
            <Link href="/products">{t.nav.products}</Link>
            <span className="breadcrumb-sep">›</span>
            <span className="breadcrumb-current">{name}</span>
          </div>

          {/* Product Main */}
          <div className={styles.productMain}>
            {/* Gallery */}
            <div className={styles.gallery}>
              <div className={styles.mainImage}>
                <div className={styles.imgPlaceholder}>
                  <span style={{ fontSize: '8rem' }}>
                    {product.category === 'smartphones' ? '📱' : product.category === 'tablets' ? '💻' : product.category === 'watches' ? '⌚' : product.category === 'gaming' ? '🎮' : '🎧'}
                  </span>
                </div>
                {product.discount && (
                  <div className={styles.galleryBadge}>
                    <span className="badge badge-orange">-{product.discount}%</span>
                  </div>
                )}
              </div>
            </div>

            {/* Info */}
            <div className={styles.info}>
              {/* Brand & Title */}
              <div className={styles.brand}>{product.brand}</div>
              <h1 className={styles.title}>{name}</h1>

              {/* Rating */}
              <div className={styles.ratingRow}>
                <span style={{ color: 'var(--warning)' }}>{'★'.repeat(Math.round(product.rating))}</span>
                <span className={styles.ratingNum}>{product.rating}</span>
                <span className={styles.ratingCount}>({product.reviewCount} {t.product.reviews})</span>
                <span className={`${styles.stockBadge} ${product.inStock ? styles.inStock : styles.outOfStock}`}>
                  {product.inStock ? `✓ ${t.product.inStock}` : `✗ ${t.product.outOfStock}`}
                </span>
              </div>

              {/* Price */}
              <div className={styles.priceRow}>
                <span className={styles.price}>{product.price.toFixed(3)} {t.product.kwd}</span>
                {product.originalPrice && (
                  <>
                    <span className={styles.originalPrice}>{product.originalPrice.toFixed(3)} {t.product.kwd}</span>
                    <span className="badge badge-orange">{language === 'ar' ? `وفر ${(product.originalPrice - product.price).toFixed(3)} د.ك` : `Save ${(product.originalPrice - product.price).toFixed(3)} KWD`}</span>
                  </>
                )}
              </div>

              <p className={styles.desc}>{desc}</p>

              {/* Variants */}
              {product.specs.colors && product.specs.colors.length > 0 && (
                <div className={styles.variantsRow}>
                  <label className="form-label">{language === 'ar' ? 'اللون:' : 'Color:'} <span style={{ color: 'var(--text-primary)', fontWeight: '600' }}>{selectedColor}</span></label>
                  <div style={{ display: 'flex', gap: '10px', marginTop: '8px' }}>
                    {product.specs.colors.map(color => (
                        <button 
                          key={color} 
                          onClick={() => setSelectedColor(color)}
                          style={{
                            padding: '8px 16px',
                            background: selectedColor === color ? 'rgba(0,209,255,0.1)' : 'rgba(255,255,255,0.05)',
                            border: `1px solid ${selectedColor === color ? 'var(--electric-blue)' : 'rgba(255,255,255,0.1)'}`,
                            borderRadius: '8px',
                            color: selectedColor === color ? 'var(--electric-blue)' : 'var(--text-secondary)',
                            fontSize: '0.85rem',
                            cursor: 'pointer',
                            transition: 'var(--transition-fast)'
                          }}
                        >
                          {color}
                        </button>
                    ))}
                  </div>
                </div>
              )}
              
              {product.category === 'smartphones' && (
                <div className={styles.variantsRow} style={{ marginTop: '16px' }}>
                  <label className="form-label">{language === 'ar' ? 'السعة:' : 'Storage:'}</label>
                  <div style={{ display: 'flex', gap: '10px', marginTop: '8px' }}>
                    {['128GB', '256GB', '512GB', '1TB'].map(storage => (
                        <button 
                          key={storage} 
                          onClick={() => setSelectedStorage(storage)}
                          style={{
                            padding: '8px 16px',
                            background: selectedStorage.includes(storage) ? 'rgba(0,209,255,0.1)' : 'rgba(255,255,255,0.05)',
                            border: `1px solid ${selectedStorage.includes(storage) ? 'var(--electric-blue)' : 'rgba(255,255,255,0.1)'}`,
                            borderRadius: '8px',
                            color: selectedStorage.includes(storage) ? 'var(--electric-blue)' : 'var(--text-secondary)',
                            fontSize: '0.85rem',
                            cursor: 'pointer',
                            transition: 'var(--transition-fast)'
                          }}
                        >
                          {storage}
                        </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Quantity */}
              <div className={styles.qtyRow}>
                <label className="form-label">{language === 'ar' ? 'الكمية:' : 'Quantity:'}</label>
                <div className={styles.qtyControl}>
                  <button className={styles.qtyBtn} onClick={() => setQty(q => Math.max(1, q - 1))}>−</button>
                  <span className={styles.qtyNum}>{qty}</span>
                  <button className={styles.qtyBtn} onClick={() => setQty(q => q + 1)}>+</button>
                </div>
              </div>

              {/* Actions */}
              <div className={styles.actions}>
                <button className="btn btn-primary btn-lg" onClick={handleAddToCart} disabled={!product.inStock} style={{ flex: 2 }}>
                  🛒 {t.product.addToCart}
                </button>
                <button className={`btn btn-outline ${isWishlisted(product.id) ? 'btn-outline-orange' : ''}`} onClick={handleWishlist} title={t.product.addToWishlist}>
                  {isWishlisted(product.id) ? '❤️' : '🤍'}
                </button>
                <button className={`btn btn-outline ${isComparing(product.id) ? 'btn-outline-orange' : ''}`} onClick={handleCompare} title={t.product.compare}>
                  ⚖️
                </button>
              </div>

              {/* Meta */}
              <div className={styles.meta}>
                <div className={styles.metaRow}><span>{t.productDetail.warranty}:</span><span>{product.warranty} {t.productDetail.months}</span></div>
                <div className={styles.metaRow}><span>{t.productDetail.brand}:</span><span>{product.brand}</span></div>
                <div className={styles.metaRow}><span>{t.productDetail.sku}:</span><span>FTP-{product.id}</span></div>
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div className={styles.tabs}>
            <button className={`${styles.tab} ${activeTab === 'specs' ? styles.tabActive : ''}`} onClick={() => setActiveTab('specs')}>
              📊 {t.productDetail.specs}
            </button>
            <button className={`${styles.tab} ${activeTab === 'reviews' ? styles.tabActive : ''}`} onClick={() => setActiveTab('reviews')}>
              💬 {t.productDetail.reviews} ({product.reviewCount})
            </button>
          </div>

          {/* Tab Content */}
          <div className={styles.tabContent}>
            {activeTab === 'specs' && (
              <div className={styles.specsTable}>
                {specRows.map(([label, value]) => (
                  <div key={label} className={styles.specRow}>
                    <span className={styles.specLabel}>{label}</span>
                    <span className={styles.specValue}>{value}</span>
                  </div>
                ))}
              </div>
            )}
            {activeTab === 'reviews' && (
              <div className={styles.reviewsList}>
                {reviews.length === 0 && <div className={styles.reviewItem} style={{ textAlign: 'center', color: 'var(--text-muted)' }}>No reviews yet. Be the first to review!</div>}
                {reviews.map((r, i) => (
                  <div key={i} className={styles.reviewItem}>
                    <div className={styles.reviewHeader}>
                      <div className={styles.reviewAvatar}>{r.userName[0]}</div>
                      <div>
                        <div className={styles.reviewName}>{r.userName}</div>
                        <div style={{ color: 'var(--warning)', fontSize: '0.85rem' }}>{'★'.repeat(r.rating)}</div>
                      </div>
                      <span className={styles.reviewDate}>{new Date(r.createdAt).toLocaleDateString()}</span>
                    </div>
                    <p className={styles.reviewComment}>{r.comment}</p>
                  </div>
                ))}
                
                {(!reviews.some(r => r.userId === user?.id)) && (
                  <div className={styles.reviewItem} style={{ marginTop: '32px' }}>
                    <h3 style={{ marginBottom: '16px', color: 'var(--text-primary)' }}>{t.productDetail.writeReview}</h3>
                    {user ? (
                      <form onSubmit={submitReview}>
                        <div style={{ marginBottom: '16px' }}>
                          <label className="form-label" style={{ display: 'block', marginBottom: '8px' }}>Rating</label>
                          <div style={{ display: 'flex', gap: '8px' }}>
                            {[1,2,3,4,5].map(star => (
                              <button
                                key={star}
                                type="button"
                                onClick={() => setReviewForm({ ...reviewForm, rating: star })}
                                style={{
                                  background: 'none',
                                  border: 'none',
                                  fontSize: '1.5rem',
                                  cursor: 'pointer',
                                  color: star <= reviewForm.rating ? 'var(--warning)' : 'rgba(255,255,255,0.2)'
                                }}
                              >
                                ★
                              </button>
                            ))}
                          </div>
                        </div>
                        <div style={{ marginBottom: '16px' }}>
                          <label className="form-label">Review</label>
                          <textarea 
                            className="form-input" 
                            rows={4} 
                            placeholder="Share your experience..." 
                            value={reviewForm.comment}
                            onChange={e => setReviewForm({ ...reviewForm, comment: e.target.value })}
                            required
                          />
                        </div>
                        <button type="submit" className="btn btn-primary" disabled={submittingReview}>
                          {submittingReview ? 'Submitting...' : t.reviews.submit}
                        </button>
                      </form>
                    ) : (
                      <div style={{ padding: '20px', background: 'rgba(255,122,0,0.1)', borderRadius: '12px', border: '1px solid rgba(255,122,0,0.2)' }}>
                        <p style={{ marginBottom: '12px' }}>You must be logged in to post a review.</p>
                        <Link href="/auth/login" className="btn btn-outline btn-sm">Sign In / Register</Link>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Related */}
          {related.length > 0 && (
            <div style={{ marginTop: '60px' }}>
              <h2 className="section-title" style={{ marginBottom: '24px' }}>🔗 {t.productDetail.related}</h2>
              <div className="products-grid">
                {related.map(p => <ProductCard key={p.id} product={p} />)}
              </div>
            </div>
          )}
        </div>
      </div>
    </StoreLayout>
  );
}
