'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { useLanguage } from '@/context/LanguageContext';
import { getAdminStats, getAdminRecentOrders, getAdminProducts } from '@/lib/admin-actions';
import SimpleChart from '@/components/ui/SimpleChart';
import styles from './admin.module.css';

const statusColors: Record<string, string> = {
  placed: 'var(--text-muted)',
  paid: 'var(--electric-blue)',
  preparing: 'var(--warning)',
  shipped: '#9B59B6',
  delivered: 'var(--success)',
  cancelled: 'var(--error)'
};

export default function AdminDashboard() {
  const { user, logout, isAdmin } = useAuth();
  const { t, language } = useLanguage();
  const router = useRouter();
  const [activeSection, setActiveSection] = useState('dashboard');
  const [editProduct, setEditProduct] = useState<string | null>(null);

  const [analytics, setAnalytics] = useState<any>(null);
  const [chartData, setChartData] = useState<any[]>([]);
  const [banners, setBanners] = useState<any[]>([]);
  
  const [dbStats, setDbStats] = useState({ revenue: 0, orders: 0, products: 0, users: 0 });
  const [dbOrders, setDbOrders] = useState<any[]>([]);
  const [dbProducts, setDbProducts] = useState<any[]>([]);

  React.useEffect(() => {
    if (isAdmin) {
      // Fetch stats
      getAdminStats().then(setDbStats);
      getAdminRecentOrders().then(setDbOrders);
      getAdminProducts().then(setDbProducts);

      fetch('/api/analytics').then(r => r.json()).then(d => {
        if (d.success) {
          setAnalytics(d.summary);
          setChartData(d.daily.map((item: any) => ({
            label: new Date(item.date).toLocaleDateString(language === 'ar' ? 'ar-KW' : 'en-US', { month: 'short', day: 'numeric' }),
            value: item.revenue
          })).slice(-14)); // Last 14 days for cleaner chart
        }
      }).catch(()=>null);
      fetch('/api/banners').then(r => r.json()).then(d => { if(d.success) setBanners(d.banners); }).catch(()=>null);
    }
  }, [isAdmin, language]);

  if (!isAdmin) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', flexDirection: 'column', gap: '16px', background: 'var(--deep-black)' }}>
      <div style={{ fontSize: '3rem' }}>🔒</div>
      <h2 style={{ color: 'var(--text-primary)', fontFamily: 'Orbitron, sans-serif' }}>Access Denied</h2>
      <div style={{ display: 'flex', gap: '12px' }}>
        <Link href="/auth/login" className="btn btn-primary">Login as Admin</Link>
        <Link href="/" className="btn btn-ghost">Back to Store</Link>
      </div>
    </div>
  );

  const navItems = [
    { id: 'dashboard', icon: '📊', label: t.admin.dashboard },
    { id: 'products', icon: '📱', label: t.admin.products },
    { id: 'orders', icon: '📦', label: t.admin.orders },
    { id: 'users', icon: '👥', label: t.admin.users },
    { id: 'reviews', icon: '⭐', label: t.admin.reviews },
    { id: 'banners', icon: '🖼️', label: t.admin.banners },
    { id: 'offers', icon: '🎁', label: t.admin.offers },
  ];

  return (
    <div className={styles.wrapper} dir={language === 'ar' ? 'rtl' : 'ltr'}>
      {/* Sidebar */}
      <aside className={styles.sidebar}>
        <div className={styles.sidebarTop}>
          <Link href="/" className={styles.brandLink}>
            <div className={styles.brandLogo}>⚡</div>
            <div>
              <div className={styles.brandName}>FAST TIME</div>
              <div className={styles.brandSub}>{language === 'ar' ? 'لوحة التحكم' : 'Admin Panel'}</div>
            </div>
          </Link>
        </div>

        <nav className={styles.sideNav}>
          {navItems.map(item => (
            <button key={item.id} className={`${styles.navItem} ${activeSection === item.id ? styles.navActive : ''}`} onClick={() => setActiveSection(item.id)}>
              <span>{item.icon}</span>
              <span>{item.label}</span>
            </button>
          ))}
        </nav>

        <div className={styles.sidebarBottom}>
          <div className={styles.adminUser}>
            <div className={styles.adminAvatar}>{user?.name?.[0] || 'A'}</div>
            <div>
              <div style={{ fontSize: '0.85rem', fontWeight: '600', color: 'var(--text-primary)' }}>{user?.name}</div>
              <div style={{ fontSize: '0.72rem', color: 'var(--electric-blue)' }}>{language === 'ar' ? 'مسؤول' : 'Admin'}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
            <Link href="/" className="btn btn-ghost btn-sm" style={{ flex: 1 }}>🏪 {language === 'ar' ? 'المتجر' : 'Store'}</Link>
            <button className="btn btn-outline btn-sm" onClick={() => { logout(); router.push('/'); }}>
              {t.header.logout}
            </button>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <main className={styles.main}>
        {/* Top Bar */}
        <div className={styles.topBar}>
          <h1 className={styles.pageTitle}>
            {navItems.find(n => n.id === activeSection)?.icon} {' '}
            {navItems.find(n => n.id === activeSection)?.label}
          </h1>
          <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
            <Link href="/products" className="btn btn-outline btn-sm" target="_blank">👁️ {language === 'ar' ? 'عرض المتجر' : 'View Store'}</Link>
          </div>
        </div>

        {/* DASHBOARD */}
        {activeSection === 'dashboard' && (
          <div className={styles.content}>
            {/* Stats */}
            <div className={styles.statsGrid}>
              {[
                { label: t.admin.totalRevenue, value: `${dbStats.revenue.toLocaleString('en')} KWD`, icon: '💰', color: 'var(--electric-blue)' },
                { label: t.admin.totalOrders, value: dbStats.orders, icon: '📦', color: 'var(--neon-orange)' },
                { label: t.admin.totalProducts, value: dbStats.products, icon: '📱', color: '#9B59B6' },
                { label: t.admin.totalUsers, value: dbStats.users.toLocaleString(), icon: '👥', color: 'var(--success)' },
              ].map((stat, i) => (
                <div key={i} className={styles.statCard}>
                  <div className={styles.statIcon} style={{ background: `${stat.color}18`, color: stat.color }}>{stat.icon}</div>
                  <div>
                    <div className={styles.statValue} style={{ color: stat.color }}>{stat.value}</div>
                    <div className={styles.statLabel}>{stat.label}</div>
                  </div>
                </div>
              ))}
            </div>

            {/* Revenue Chart */}
            <div className={styles.card} style={{ marginTop: '24px' }}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{language === 'ar' ? 'الإيرادات (آخر 14 يوم)' : 'Revenue (Last 14 Days)'}</h3>
              </div>
              <SimpleChart data={chartData} height={250} formatValue={v => `${v} KWD`} />
            </div>

            {/* Recent Orders */}
            <div className={styles.card} style={{ marginTop: '24px' }}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{t.admin.recentOrders}</h3>
                <button className="btn btn-outline btn-sm" onClick={() => setActiveSection('orders')}>{language === 'ar' ? 'عرض الكل' : 'View All'}</button>
              </div>
              <div className={styles.tableWrap}>
                <table className={styles.table}>
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>{language === 'ar' ? 'العميل' : 'Customer'}</th>
                      <th>{language === 'ar' ? 'المنتج' : 'Product'}</th>
                      <th>{language === 'ar' ? 'المبلغ' : 'Amount'}</th>
                      <th>{t.admin.status}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dbOrders.slice(0, 5).map(ord => (
                      <tr key={ord.id}>
                        <td><span style={{ fontFamily: 'Orbitron, monospace', fontSize: '0.8rem' }}>{ord.id.slice(-6)}</span></td>
                        <td>{ord.customerName}</td>
                        <td>{ord.items.length} Items</td>
                        <td><span style={{ color: 'var(--electric-blue)', fontFamily: 'Orbitron, monospace', fontWeight: '700' }}>{ord.total.toFixed(3)}</span></td>
                        <td><span className="badge" style={{ background: `${statusColors[ord.status]}15`, color: statusColors[ord.status] || 'var(--text-muted)', border: `1px solid ${statusColors[ord.status]}30` }}>{ord.status}</span></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* PRODUCTS */}
        {activeSection === 'products' && (
          <div className={styles.content}>
            <div className={styles.card}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{t.admin.products} ({dbProducts.length})</h3>
                <button className="btn btn-primary btn-sm">+ {t.admin.addProduct}</button>
              </div>
              <div className={styles.tableWrap}>
                <table className={styles.table}>
                  <thead>
                    <tr>
                      <th>{language === 'ar' ? 'المنتج' : 'Product'}</th>
                      <th>{language === 'ar' ? 'الماركة' : 'Brand'}</th>
                      <th>{language === 'ar' ? 'الفئة' : 'Category'}</th>
                      <th>{language === 'ar' ? 'السعر' : 'Price'}</th>
                      <th>{t.admin.status}</th>
                      <th>{t.admin.actions}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dbProducts.map(p => (
                      <tr key={p.id}>
                        <td style={{ maxWidth: '200px' }}>
                          <div style={{ fontWeight: '600', fontSize: '0.85rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{language === 'ar' ? p.nameAr : p.name}</div>
                        </td>
                        <td>{p.brand}</td>
                        <td><span className="badge badge-blue">{p.category?.name || 'General'}</span></td>
                        <td><span style={{ color: 'var(--electric-blue)', fontFamily: 'Orbitron, monospace', fontWeight: '700', fontSize: '0.85rem' }}>{p.price.toFixed(3)} KWD</span></td>
                        <td><span className={`badge ${p.stock > 0 ? 'badge-success' : 'badge-error'}`}>{p.stock > 0 ? t.admin.active : t.admin.inactive}</span></td>
                        <td>
                          <div style={{ display: 'flex', gap: '6px' }}>
                            <Link href={`/products/${p.id}`} className="btn btn-ghost btn-sm" target="_blank">👁️</Link>
                            <button className="btn btn-outline btn-sm">✏️</button>
                            <button className="btn btn-sm" style={{ background: 'rgba(255,59,92,0.1)', color: 'var(--error)' }}>🗑️</button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ORDERS */}
        {activeSection === 'orders' && (
          <div className={styles.content}>
            <div className={styles.card}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{t.admin.orders}</h3>
                <button className="btn btn-outline btn-sm">{language === 'ar' ? 'تصدير CSV' : 'Export CSV'}</button>
              </div>
              <div className={styles.tableWrap}>
                <table className={styles.table}>
                  <thead>
                    <tr>
                      <th>ID</th><th>{language === 'ar' ? 'العميل' : 'Customer'}</th>
                      <th>{language === 'ar' ? 'المنتج' : 'Product'}</th>
                      <th>{language === 'ar' ? 'المبلغ' : 'Amount'}</th>
                      <th>{t.admin.status}</th><th>{t.admin.actions}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dbOrders.map(ord => (
                      <tr key={ord.id}>
                        <td><span style={{ fontFamily: 'Orbitron, monospace', fontSize: '0.8rem' }}>{ord.id.slice(-6)}</span></td>
                        <td>{ord.customerName}</td>
                        <td style={{ maxWidth: '160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ord.items.length} Items</td>
                        <td><span style={{ color: 'var(--electric-blue)', fontFamily: 'Orbitron, monospace', fontWeight: '700' }}>{ord.total.toFixed(3)}</span></td>
                        <td>
                          <select className="form-input" style={{ padding: '4px 8px', fontSize: '0.78rem', width: 'auto' }} defaultValue={ord.status}>
                            {['placed','paid','preparing','shipped','delivered', 'cancelled'].map(s => <option key={s} value={s}>{s}</option>)}
                          </select>
                        </td>
                        <td><button className="btn btn-primary btn-sm">{language === 'ar' ? 'حفظ' : 'Save'}</button></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* BANNERS */}
        {activeSection === 'banners' && (
          <div className={styles.content}>
            <div className={styles.card}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{t.admin.banners}</h3>
                <button className="btn btn-primary btn-sm">+ Add Banner</button>
              </div>
              <p style={{ color: 'var(--text-muted)', marginBottom: '16px' }}>Manage the hero sliders strictly on the Home Page.</p>
              <div className="products-grid">
                {banners.length > 0 ? banners.map(b => (
                  <div key={b.id} style={{ background: 'rgba(255,255,255,0.05)', padding: '16px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.1)' }}>
                    <div style={{ fontWeight: '600', marginBottom: '8px', color: 'var(--electric-blue)' }}>{b.title}</div>
                    <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '12px' }}>{b.subtitle}</div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <span className={`badge ${b.active ? 'badge-success' : 'badge-error'}`}>{b.active ? 'Active' : 'Inactive'}</span>
                      <button className="btn btn-outline btn-sm" style={{ flex: 1 }}>Edit</button>
                    </div>
                  </div>
                )) : (
                  <div style={{ padding: '20px', color: 'var(--text-muted)' }}>No banners configured yet.</div>
                )}
              </div>
            </div>
          </div>
        )}

        {/* OFFERS */}
        {activeSection === 'offers' && (
          <div className={styles.content}>
            <div className={styles.card}>
              <div className={styles.cardHeader}>
                <h3 className={styles.cardTitle}>{t.admin.offers}</h3>
                <button className="btn btn-primary btn-sm">+ Create Smart Offer</button>
              </div>
              <div style={{ display: 'grid', gap: '16px' }}>
                <div style={{ background: 'rgba(255,122,0,0.1)', padding: '20px', borderRadius: '12px', border: '1px solid rgba(255,122,0,0.3)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <h4 style={{ color: 'var(--neon-orange)', marginBottom: '4px' }}>Welcome Discount</h4>
                      <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>10% off for first-time buyers on any order.</div>
                    </div>
                    <span className="badge badge-orange">Active</span>
                  </div>
                </div>
                <div style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.1)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <h4 style={{ color: 'var(--electric-blue)', marginBottom: '4px' }}>Bundle Saver</h4>
                      <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>Buy iPhone + AirPods and save 15 KWD.</div>
                    </div>
                    <span className="badge">Inactive</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* OTHER SECTIONS */}
        {['users', 'reviews'].includes(activeSection) && (
          <div className={styles.content}>
            <div className={styles.card} style={{ textAlign: 'center', padding: '60px 24px' }}>
              <div style={{ fontSize: '3rem', marginBottom: '16px' }}>🔧</div>
              <h3 className={styles.cardTitle}>{navItems.find(n => n.id === activeSection)?.label}</h3>
              <p style={{ color: 'var(--text-muted)', marginTop: '8px' }}>{language === 'ar' ? 'قريباً في التحديث القادم' : 'Coming in next update'}</p>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
