import { useEffect, useState } from 'react';
import AdminLayout from '../../components/AdminLayout';
import { getProducts, createProduct, updateProduct, deleteProduct } from '../../utils/api';
import axios from 'axios';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;

const AdminProducts = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [formData, setFormData] = useState({
    name: '', description: '', price: 0, original_price: 0,
    category: 'Spareparts', brand: '', stock: 0, images: [],
    is_available: true, featured: false
  });

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

  const loadProducts = async () => {
    try {
      const response = await getProducts();
      setProducts(response.data);
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleImageUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setUploading(true);
    try {
      const formDataUpload = new FormData();
      formDataUpload.append('file', file);
      const token = localStorage.getItem('admin_token');
      const response = await axios.post(`${BACKEND_URL}/api/upload-image`, formDataUpload, {
        headers: { 'Content-Type': 'multipart/form-data', 'Authorization': `Bearer ${token}` }
      });
      setFormData(prev => ({ ...prev, images: [...prev.images, response.data.url] }));
    } catch (error) {
      alert('Upload failed');
    } finally {
      setUploading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await updateProduct(editingId, formData);
      } else {
        await createProduct(formData);
      }
      await loadProducts();
      resetForm();
    } catch (error) {
      alert('Failed to save');
    }
  };

  const handleEdit = (product) => {
    setEditingId(product.id);
    setFormData(product);
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete?')) return;
    try {
      await deleteProduct(id);
      await loadProducts();
    } catch (error) {
      alert('Failed to delete');
    }
  };

  const resetForm = () => {
    setEditingId(null);
    setFormData({ name: '', description: '', price: 0, original_price: 0, category: 'Spareparts', brand: '', stock: 0, images: [], is_available: true, featured: false });
  };

  const removeImage = (index) => {
    setFormData(prev => ({ ...prev, images: prev.images.filter((_, i) => i !== index) }));
  };

  if (loading) return <AdminLayout><div className="text-center py-20">Loading...</div></AdminLayout>;

  return (
    <AdminLayout>
      <h1 className="text-3xl font-extrabold text-gray-900 mb-8">🛍️ Manage Products</h1>

      <div className="grid md:grid-cols-2 gap-8">
        {/* Form */}
        <div className="bg-white rounded-2xl shadow-sm border p-6">
          <h2 className="text-xl font-bold mb-6">{editingId ? 'Edit' : 'Add'} Product</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block font-semibold mb-2">Name *</label>
              <input type="text" value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} className="w-full px-4 py-3 border rounded-xl" required />
            </div>
            <div>
              <label className="block font-semibold mb-2">Description *</label>
              <textarea value={formData.description} onChange={(e) => setFormData({...formData, description: e.target.value})} className="w-full px-4 py-3 border rounded-xl" rows="3" required />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block font-semibold mb-2">Price *</label>
                <input type="number" value={formData.price} onChange={(e) => setFormData({...formData, price: parseFloat(e.target.value)})} className="w-full px-4 py-3 border rounded-xl" required />
              </div>
              <div>
                <label className="block font-semibold mb-2">Original Price</label>
                <input type="number" value={formData.original_price} onChange={(e) => setFormData({...formData, original_price: parseFloat(e.target.value)})} className="w-full px-4 py-3 border rounded-xl" />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block font-semibold mb-2">Category</label>
                <select value={formData.category} onChange={(e) => setFormData({...formData, category: e.target.value})} className="w-full px-4 py-3 border rounded-xl">
                  <option>Spareparts</option>
                  <option>Aksesoris</option>
                  <option>Elektronik</option>
                </select>
              </div>
              <div>
                <label className="block font-semibold mb-2">Stock</label>
                <input type="number" value={formData.stock} onChange={(e) => setFormData({...formData, stock: parseInt(e.target.value)})} className="w-full px-4 py-3 border rounded-xl" />
              </div>
            </div>
            <div>
              <label className="block font-semibold mb-2">Brand</label>
              <input type="text" value={formData.brand} onChange={(e) => setFormData({...formData, brand: e.target.value})} className="w-full px-4 py-3 border rounded-xl" />
            </div>
            <div>
              <label className="block font-semibold mb-2">Images</label>
              <input type="file" accept="image/*" onChange={handleImageUpload} className="w-full px-4 py-3 border rounded-xl" disabled={uploading} />
              {uploading && <p className="text-blue-600 text-sm mt-2">Uploading...</p>}
              <div className="flex gap-2 mt-3">
                {formData.images.map((img, i) => (
                  <div key={i} className="relative">
                    <img src={img} className="w-20 h-20 object-cover rounded" />
                    <button type="button" onClick={() => removeImage(i)} className="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-6 h-6">×</button>
                  </div>
                ))}
              </div>
            </div>
            <div className="flex gap-4">
              <label className="flex items-center gap-2">
                <input type="checkbox" checked={formData.is_available} onChange={(e) => setFormData({...formData, is_available: e.target.checked})} />
                Available
              </label>
              <label className="flex items-center gap-2">
                <input type="checkbox" checked={formData.featured} onChange={(e) => setFormData({...formData, featured: e.target.checked})} />
                Featured
              </label>
            </div>
            <div className="flex gap-3">
              <button type="submit" className="bg-blue-600 text-white px-6 py-3 rounded-xl font-bold hover:bg-blue-700">{editingId ? 'Update' : 'Add'}</button>
              {editingId && <button type="button" onClick={resetForm} className="bg-gray-200 px-6 py-3 rounded-xl font-bold">Cancel</button>}
            </div>
          </form>
        </div>

        {/* List */}
        <div className="bg-white rounded-2xl shadow-sm border p-6">
          <h2 className="text-xl font-bold mb-6">Products ({products.length})</h2>
          <div className="space-y-3 max-h-[800px] overflow-y-auto">
            {products.map((product) => (
              <div key={product.id} className="border rounded-xl p-4">
                <div className="flex gap-4">
                  {product.images[0] && <img src={product.images[0]} className="w-20 h-20 object-cover rounded" />}
                  <div className="flex-1">
                    <h3 className="font-bold">{product.name}</h3>
                    <p className="text-sm text-gray-600">{product.category} • Stok: {product.stock}</p>
                    <p className="text-blue-600 font-bold">Rp {product.price.toLocaleString()}</p>
                  </div>
                  <div className="flex gap-2">
                    <button onClick={() => handleEdit(product)} className="text-blue-600 font-semibold">Edit</button>
                    <button onClick={() => handleDelete(product.id)} className="text-red-600 font-semibold">Del</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdminProducts;
