'use client';

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

export default function ComparePage() {
  const { products: compareList, removeProduct, clearAll } = useCompare();
  const { addItem } = useCart();
  const { t, language } = useLanguage();
  const suggestions = products.filter(p => !compareList.find(c => c.id === p.id)).slice(0, 4);

  const specKeys: { key: keyof typeof compareList[0]['specs']; label: string; labelAr: string }[] = [
    { key: 'display', label: 'Display', labelAr: 'الشاشة' },
    { key: 'processor', label: 'Processor', labelAr: 'المعالج' },
    { key: 'ram', label: 'RAM', labelAr: 'الذاكرة' },
    { key: 'storage', label: 'Storage', labelAr: 'التخزين' },
    { key: 'battery', label: 'Battery', labelAr: 'البطارية' },
    { key: 'camera', label: 'Camera', labelAr: 'الكاميرا' },
    { key: 'os', label: 'OS', labelAr: 'النظام' },
  ];

  const bestValue = compareList.reduce((best, p) => !best || p.price < best.price ? p : best, compareList[0]);
  const bestPerf = compareList.reduce((best, p) => !best || p.price > best.price ? p : best, compareList[0]);

  if (compareList.length === 0) return (
    <StoreLayout>
      <div style={{ minHeight: '60vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '20px', textAlign: 'center', padding: '60px 24px' }}>
        <div style={{ fontSize: '4rem' }}>⚖️</div>
        <h2 style={{ fontFamily: 'Orbitron, Cairo, sans-serif', color: 'var(--text-primary)' }}>{t.compare.noProducts}</h2>
        <p style={{ color: 'var(--text-muted)' }}>{t.compare.subtitle}</p>
        <div className="products-grid" style={{ marginTop: '20px', width: '100%', maxWidth: '900px' }}>
          {suggestions.map(p => <ProductCard key={p.id} product={p} />)}
        </div>
      </div>
    </StoreLayout>
  );

  return (
    <StoreLayout>
      <div className="container" style={{ padding: '30px 24px 80px' }}>
        <div className={styles.header}>
          <div>
            <h1 className={styles.title}>⚖️ {t.compare.title}</h1>
            <p className="text-secondary" style={{ fontSize: '0.9rem' }}>{t.compare.subtitle}</p>
          </div>
          <button className="btn btn-outline" onClick={clearAll}>{t.compare.clear}</button>
        </div>

        <div className={styles.table}>
          {/* Header Row */}
          <div className={styles.row}>
            <div className={styles.labelCell}>{language === 'ar' ? 'المنتج' : 'Product'}</div>
            {compareList.map(p => (
              <div key={p.id} className={styles.cell}>
                <div className={styles.productHeader}>
                  {p.id === bestValue?.id && <span className="badge badge-success">{t.compare.bestValue}</span>}
                  {p.id === bestPerf?.id && compareList.length > 1 && <span className="badge badge-blue">{t.compare.bestPerformance}</span>}
                  <div className={styles.productIcon}>
                    <span style={{ fontSize: '3rem' }}>📱</span>
                  </div>
                  <div className={styles.productName}>{language === 'ar' ? p.nameAr : p.name}</div>
                  <div className={styles.productPrice}>{p.price.toFixed(3)} {t.product.kwd}</div>
                  <div style={{ display: 'flex', gap: '6px', marginTop: '8px' }}>
                    <button className="btn btn-primary btn-sm" onClick={() => addItem({ id: p.id, name: p.name, nameAr: p.nameAr, price: p.price, image: p.image, slug: p.slug })}>
                      🛒 {t.product.addToCart}
                    </button>
                    <button className="btn btn-ghost btn-sm" onClick={() => removeProduct(p.id)}>✕</button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Spec Rows */}
          {specKeys.map(spec => (
            <div key={spec.key} className={styles.row}>
              <div className={styles.labelCell}>{language === 'ar' ? spec.labelAr : spec.label}</div>
              {compareList.map(p => (
                <div key={p.id} className={styles.cell}>
                  <span className={styles.specVal}>{p.specs[spec.key] || '—'}</span>
                </div>
              ))}
            </div>
          ))}
        </div>

        {/* Suggestions */}
        {suggestions.length > 0 && (
          <div style={{ marginTop: '60px' }}>
            <h2 style={{ fontFamily: 'Orbitron, Cairo, sans-serif', fontSize: '1.2rem', color: 'var(--text-primary)', marginBottom: '24px' }}>
              {language === 'ar' ? '➕ أضف إلى المقارنة' : '➕ Add to Compare'}
            </h2>
            <div className="products-grid">
              {suggestions.map(p => <ProductCard key={p.id} product={p} />)}
            </div>
          </div>
        )}
      </div>
    </StoreLayout>
  );
}
