import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Plus, Search, Edit2, Trash2, PackagePlus } from 'lucide-react';
import api from '../services/api';
import { useAuth } from '../context/AuthContext';
import Modal from '../components/Modal';
import Alert from '../components/Alert';
import { formatCurrency } from '../utils/helpers';

const emptyProduct = {
  name: '',
  sku: '',
  description: '',
  category_id: '',
  quantity: 0,
  min_stock_level: 10,
  unit_price: 0,
  supplier: '',
  location: '',
};

export default function Products() {
  const [products, setProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [stockModalOpen, setStockModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [form, setForm] = useState(emptyProduct);
  const [stockForm, setStockForm] = useState({ type: 'in', quantity: '', reason: '', reference_no: '' });
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const { hasRole } = useAuth();
  const [searchParams] = useSearchParams();
  const lowStockOnly = searchParams.get('low_stock') === 'true';

  const canManage = hasRole('admin', 'manager');
  const canAdjustStock = hasRole('admin', 'manager', 'staff');

  const fetchProducts = () => {
    const params = {};
    if (search) params.search = search;
    if (lowStockOnly) params.low_stock = 'true';

    api.get('/products', { params })
      .then((res) => setProducts(res.data.products))
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    api.get('/categories').then((res) => setCategories(res.data.categories)).catch(console.error);
  }, []);

  useEffect(() => {
    setLoading(true);
    const timer = setTimeout(fetchProducts, 300);
    return () => clearTimeout(timer);
  }, [search, lowStockOnly]);

  const openCreateModal = () => {
    setEditingProduct(null);
    setForm(emptyProduct);
    setError('');
    setModalOpen(true);
  };

  const openEditModal = (product) => {
    setEditingProduct(product);
    setForm({
      name: product.name,
      sku: product.sku,
      description: product.description || '',
      category_id: product.category_id || '',
      quantity: product.quantity,
      min_stock_level: product.min_stock_level,
      unit_price: product.unit_price,
      supplier: product.supplier || '',
      location: product.location || '',
    });
    setError('');
    setModalOpen(true);
  };

  const openStockModal = (product) => {
    setSelectedProduct(product);
    setStockForm({ type: 'in', quantity: '', reason: '', reference_no: '' });
    setError('');
    setStockModalOpen(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    try {
      if (editingProduct) {
        await api.put(`/products/${editingProduct.id}`, form);
        setSuccess('Product updated successfully');
      } else {
        await api.post('/products', form);
        setSuccess('Product created successfully');
      }
      setModalOpen(false);
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed');
    }
  };

  const handleStockSubmit = async (e) => {
    e.preventDefault();
    setError('');
    try {
      await api.post(`/products/${selectedProduct.id}/stock`, {
        ...stockForm,
        quantity: parseInt(stockForm.quantity, 10),
      });
      setSuccess('Stock updated successfully');
      setStockModalOpen(false);
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Stock update failed');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this product?')) return;
    try {
      await api.delete(`/products/${id}`);
      setSuccess('Product deleted');
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
    }
  };

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Products</h1>
          <p className="text-gray-500 mt-1">
            {lowStockOnly ? 'Showing low stock items' : 'Manage your product inventory'}
          </p>
        </div>
        {canManage && (
          <button onClick={openCreateModal} className="btn-primary">
            <Plus size={18} /> Add Product
          </button>
        )}
      </div>

      <Alert type="success" message={success} onClose={() => setSuccess('')} />
      <Alert type="error" message={error} onClose={() => setError('')} />

      <div className="card mb-6">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
          <input
            type="text"
            className="input pl-10"
            placeholder="Search by name, SKU, or supplier..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      <div className="card overflow-x-auto">
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-4 border-primary-600 border-t-transparent" />
          </div>
        ) : products.length === 0 ? (
          <p className="text-center text-gray-500 py-12">No products found</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b text-left text-gray-500">
                <th className="pb-3 font-medium">Product</th>
                <th className="pb-3 font-medium">SKU</th>
                <th className="pb-3 font-medium">Category</th>
                <th className="pb-3 font-medium">Qty</th>
                <th className="pb-3 font-medium">Price</th>
                <th className="pb-3 font-medium">Value</th>
                <th className="pb-3 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {products.map((p) => (
                <tr key={p.id} className="border-b last:border-0 hover:bg-gray-50">
                  <td className="py-3">
                    <p className="font-medium">{p.name}</p>
                    {p.quantity <= p.min_stock_level && (
                      <span className="text-xs text-red-600 font-medium">Low Stock</span>
                    )}
                  </td>
                  <td className="py-3 text-gray-600">{p.sku}</td>
                  <td className="py-3 text-gray-600">{p.category_name || '—'}</td>
                  <td className="py-3">
                    <span className={p.quantity <= p.min_stock_level ? 'text-red-600 font-semibold' : ''}>
                      {p.quantity}
                    </span>
                  </td>
                  <td className="py-3">{formatCurrency(p.unit_price)}</td>
                  <td className="py-3 font-medium">{formatCurrency(p.total_value)}</td>
                  <td className="py-3">
                    <div className="flex items-center gap-1">
                      {canAdjustStock && (
                        <button
                          onClick={() => openStockModal(p)}
                          className="p-1.5 text-green-600 hover:bg-green-50 rounded"
                          title="Adjust Stock"
                        >
                          <PackagePlus size={16} />
                        </button>
                      )}
                      {canManage && (
                        <>
                          <button
                            onClick={() => openEditModal(p)}
                            className="p-1.5 text-blue-600 hover:bg-blue-50 rounded"
                            title="Edit"
                          >
                            <Edit2 size={16} />
                          </button>
                          {hasRole('admin') && (
                            <button
                              onClick={() => handleDelete(p.id)}
                              className="p-1.5 text-red-600 hover:bg-red-50 rounded"
                              title="Delete"
                            >
                              <Trash2 size={16} />
                            </button>
                          )}
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editingProduct ? 'Edit Product' : 'Add Product'}
        size="lg"
      >
        <Alert type="error" message={error} onClose={() => setError('')} />
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="label">Product Name *</label>
              <input className="input" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
            </div>
            <div>
              <label className="label">SKU *</label>
              <input className="input" value={form.sku} onChange={(e) => setForm({ ...form, sku: e.target.value })} required />
            </div>
            <div>
              <label className="label">Category</label>
              <select className="input" value={form.category_id} onChange={(e) => setForm({ ...form, category_id: e.target.value })}>
                <option value="">Select category</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            {!editingProduct && (
              <div>
                <label className="label">Initial Quantity</label>
                <input type="number" min="0" className="input" value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} />
              </div>
            )}
            <div>
              <label className="label">Min Stock Level</label>
              <input type="number" min="0" className="input" value={form.min_stock_level} onChange={(e) => setForm({ ...form, min_stock_level: e.target.value })} />
            </div>
            <div>
              <label className="label">Unit Price ($)</label>
              <input type="number" min="0" step="0.01" className="input" value={form.unit_price} onChange={(e) => setForm({ ...form, unit_price: e.target.value })} />
            </div>
            <div>
              <label className="label">Supplier</label>
              <input className="input" value={form.supplier} onChange={(e) => setForm({ ...form, supplier: e.target.value })} />
            </div>
            <div>
              <label className="label">Location</label>
              <input className="input" value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
            </div>
          </div>
          <div>
            <label className="label">Description</label>
            <textarea className="input" rows={3} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={() => setModalOpen(false)} className="btn-secondary">Cancel</button>
            <button type="submit" className="btn-primary">{editingProduct ? 'Update' : 'Create'}</button>
          </div>
        </form>
      </Modal>

      <Modal isOpen={stockModalOpen} onClose={() => setStockModalOpen(false)} title={`Adjust Stock — ${selectedProduct?.name}`}>
        <Alert type="error" message={error} onClose={() => setError('')} />
        <p className="text-sm text-gray-500 mb-4">Current stock: <strong>{selectedProduct?.quantity}</strong></p>
        <form onSubmit={handleStockSubmit} className="space-y-4">
          <div>
            <label className="label">Type</label>
            <select className="input" value={stockForm.type} onChange={(e) => setStockForm({ ...stockForm, type: e.target.value })}>
              <option value="in">Stock In</option>
              <option value="out">Stock Out</option>
              <option value="adjustment">Adjustment (Set exact qty)</option>
            </select>
          </div>
          <div>
            <label className="label">Quantity</label>
            <input type="number" min="1" className="input" value={stockForm.quantity} onChange={(e) => setStockForm({ ...stockForm, quantity: e.target.value })} required />
          </div>
          <div>
            <label className="label">Reason</label>
            <input className="input" value={stockForm.reason} onChange={(e) => setStockForm({ ...stockForm, reason: e.target.value })} placeholder="e.g. Purchase order, Sale, Damage" />
          </div>
          <div>
            <label className="label">Reference No.</label>
            <input className="input" value={stockForm.reference_no} onChange={(e) => setStockForm({ ...stockForm, reference_no: e.target.value })} placeholder="PO-12345" />
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <button type="button" onClick={() => setStockModalOpen(false)} className="btn-secondary">Cancel</button>
            <button type="submit" className="btn-primary">Update Stock</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
