import React, { useEffect, useState } from 'react';
import productService from '../services/productService';
import './Admin.css';

const Admin = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState({ 
    name: '', 
    description: '', 
    price: '', 
    stockQuantity: 0, 
    category: '',
    imageUrl: '',
    imageUrl1: ''
  });
  const [imagePreview, setImagePreview] = useState('');
  const [imagePreview1, setImagePreview1] = useState('');
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('products');

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      setLoading(true);
      const data = await productService.getProducts({ limit: 200 });
      setProducts(data.products || []);
    } catch (err) {
      console.error(err);
      setError('Failed to load products or you may not have admin access');
    } finally {
      setLoading(false);
    }
  };

  const handleInput = (e) => setForm({ ...form, [e.target.name]: e.target.value }); 
  const handleImageUpload = (e, field) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setForm(prev => ({ ...prev, [field]: reader.result }));
        if (field === 'imageUrl') setImagePreview(reader.result);
        if (field === 'imageUrl1') setImagePreview1(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleAddProduct = async (e) => {
    e.preventDefault();
    if (!form.name || !form.price) {
      setError('Name and price are required');
      return;
    }

    const payload = {
      name: form.name,
      description: form.description,
      price: parseFloat(form.price),
      stockQuantity: parseInt(form.stockQuantity, 10) || 0,
      imageUrl: form.imageUrl,
      imageUrl1: form.imageUrl1, // Sending second image
      category: form.category,
    };

    try {
      await productService.addProduct(payload);
      setForm({ name: '', description: '', price: '', stockQuantity: 0, category: '', imageUrl: '', imageUrl1: '' });
      setImagePreview('');
      setImagePreview1('');
      fetchProducts();
      setError(null);
      alert('Product added successfully!');
    } catch (err) {
      console.error(err);
      setError(err.response?.data?.message || 'Failed to add product');
    }
  };

  const handleUpdateStock = async (id, newQty) => {
    try {
      await productService.updateProduct(id, { stockQuantity: parseInt(newQty, 10) });
      fetchProducts();
    } catch (err) {
      console.error(err);
      setError('Failed to update stock');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this product?')) return;
    try {
      await productService.deleteProduct(id);
      fetchProducts();
    } catch (err) {
      console.error(err);
      setError('Failed to delete product');
    }
  };

  return (
    <div className="admin-container">
      {/* Sidebar */}
      <aside className="admin-sidebar">
        <div className="sidebar-header">
          <span>Wraffle Admin</span>
        </div>
        <nav className="sidebar-nav">
          <a 
            href="#" 
            className={`nav-item ${activeTab === 'products' ? 'active' : ''}`}
            onClick={() => setActiveTab('products')}
          >
            📦 Products
          </a>
          <a 
            href="#" 
            className={`nav-item ${activeTab === 'orders' ? 'active' : ''}`}
            onClick={() => setActiveTab('orders')}
          >
            🛒 Orders (Coming Soon)
          </a>
          <a href="/" className="nav-item">
            🏠 Back to Site
          </a>
        </nav>
      </aside>

      {/* Main Content */}
      <main className="admin-main">
        <div className="page-header">
          <h1 className="page-title">Product Management</h1>
        </div>

        {error && <div className="admin-error">{error}</div>}

        {/* Add Product Form */}
        <section className="admin-card">
          <div className="card-header">
            <h2 className="card-title">Add New Product</h2>
          </div>
          <form onSubmit={handleAddProduct} className="admin-form">
            <div className="form-group">
              <label className="form-label">Product Name</label>
              <input className="form-input" name="name" placeholder="e.g. Summer T-Shirt" value={form.name} onChange={handleInput} />
            </div>
            
            <div className="form-group">
              <label className="form-label">Price ($)</label>
              <input className="form-input" name="price" type="number" step="0.01" placeholder="0.00" value={form.price} onChange={handleInput} />
            </div>

            <div className="form-group">
              <label className="form-label">Stock Quantity</label>
              <input className="form-input" name="stockQuantity" type="number" placeholder="0" value={form.stockQuantity} onChange={handleInput} />
            </div>

            <div className="form-group">
              <label className="form-label">Category</label>
              <input className="form-input" name="category" placeholder="e.g. Men, Women" value={form.category} onChange={handleInput} />
            </div>

            <div className="form-group full-width">
              <label className="form-label">Description</label>
              <textarea className="form-textarea" name="description" placeholder="Product details..." value={form.description} onChange={handleInput} />
            </div>

            {/* Image Uploads */}
            <div className="form-group">
              <label className="form-label">Main Image</label>
              <div className="file-upload-wrapper">
                <input type="file" accept="image/*" onChange={(e) => handleImageUpload(e, 'imageUrl')} />
                {imagePreview && <img src={imagePreview} alt="Preview" className="image-preview" />}
              </div>
            </div>

            <div className="form-group">
              <label className="form-label">Second Image</label>
              <div className="file-upload-wrapper">
                <input type="file" accept="image/*" onChange={(e) => handleImageUpload(e, 'imageUrl1')} />
                {imagePreview1 && <img src={imagePreview1} alt="Preview" className="image-preview" />}
              </div>
            </div>

            
              <div className="form-group full-width">
              <button type="submit" className="btn-primary">Add Product</button>
            </div>
          </form>
        </section>

        {/* Product List */}
        <section className="admin-card">
          <div className="card-header">
            <h2 className="card-title">Product List</h2>
          </div>
          {loading ? <p>Loading...</p> : (
            <div className="table-container">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Stock</th>
                    <th>Category</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {products.map(p => (
                    <tr key={p.id}>
                      <td>
                        {p.image_url ? (
                          <img src={p.image_url} alt={p.name} className="product-thumb" />
                        ) : (
                          <div className="product-thumb" style={{display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ccc'}}>No Img</div>
                        )}
                      </td>
                      <td>{p.name}</td>
                      <td>${p.price}</td>
                      <td>
                        <input 
                          type="number" 
                          className="form-input" 
                          style={{width: '80px'}}
                          defaultValue={p.stock_quantity} 
                          onBlur={(e) => handleUpdateStock(p.id, e.target.value)} 
                        />
                      </td>
                      <td>{p.category}</td>
                      <td>
                        <button className="action-btn" onClick={() => handleDelete(p.id)}>Delete</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </section>
      </main>
    </div>
  );
};

export default Admin;