import React, { useEffect, useState } from 'react';
import { getStocks, updateStock, deleteStock } from '../utils/api';

export default function StockStatus() {
  const [stocks, setStocks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editId, setEditId] = useState(null);
  const [editQty, setEditQty] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const fetchStocks = () => {
    setLoading(true);
    getStocks().then(r => setStocks(r.data)).catch(console.error).finally(() => setLoading(false));
  };

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

  const handleUpdate = async id => {
    setError(''); setSuccess('');
    try {
      await updateStock(id, { availableQuantity: Number(editQty) });
      setSuccess('Stock updated successfully!');
      setEditId(null);
      fetchStocks();
    } catch (err) {
      setError(err.response?.data?.message || 'Update failed');
    }
  };

  const handleDelete = async id => {
    if (!window.confirm('Delete this stock record?')) return;
    try {
      await deleteStock(id);
      setSuccess('Stock record deleted.');
      fetchStocks();
    } catch (err) {
      setError(err.response?.data?.message || 'Delete failed');
    }
  };

  const getStatusBadge = (remaining, available) => {
    if (remaining === 0) return <span className="bg-red-100 text-red-700 text-xs px-2 py-1 rounded-full font-medium">Out of Stock</span>;
    if (remaining <= 5) return <span className="bg-yellow-100 text-yellow-700 text-xs px-2 py-1 rounded-full font-medium">Low Stock</span>;
    return <span className="bg-green-100 text-green-700 text-xs px-2 py-1 rounded-full font-medium">In Stock</span>;
  };

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-slate-800">Stock Status</h1>
        <p className="text-slate-500 text-sm mt-0.5">Track available, sold, and remaining inventory</p>
      </div>

      {(error || success) && (
        <div className={`rounded-lg px-4 py-3 text-sm mb-4 ${error ? 'bg-red-50 text-red-700 border border-red-200' : 'bg-green-50 text-green-700 border border-green-200'}`}>
          {error || success}
        </div>
      )}

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100">
          <h2 className="font-semibold text-slate-800 text-sm">Inventory Overview ({stocks.length} products)</h2>
        </div>
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : stocks.length === 0 ? (
          <div className="text-center py-12 text-slate-400 text-sm">No stock records. Add products first.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50">
                <tr>
                  {['#', 'Product', 'Category', 'Available Qty', 'Sold Qty', 'Remaining Qty', 'Status', 'Actions'].map(h => (
                    <th key={h} className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {stocks.map((s, i) => (
                  <tr key={s._id} className="hover:bg-slate-50">
                    <td className="px-5 py-3 text-slate-400">{i + 1}</td>
                    <td className="px-5 py-3 font-medium text-slate-800">{s.productId?.productName || 'N/A'}</td>
                    <td className="px-5 py-3 text-slate-500 text-xs">
                      <span className="bg-blue-50 text-blue-700 px-2 py-1 rounded-full">{s.productId?.category || 'N/A'}</span>
                    </td>
                    <td className="px-5 py-3">
                      {editId === s._id ? (
                        <input
                          type="number" value={editQty} onChange={e => setEditQty(e.target.value)} min="0"
                          className="w-20 border border-blue-400 rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                        />
                      ) : (
                        <span className="text-slate-700 font-medium">{s.availableQuantity}</span>
                      )}
                    </td>
                    <td className="px-5 py-3 text-slate-600">{s.soldQuantity}</td>
                    <td className="px-5 py-3 font-semibold text-slate-800">{s.remainingQuantity}</td>
                    <td className="px-5 py-3">{getStatusBadge(s.remainingQuantity, s.availableQuantity)}</td>
                    <td className="px-5 py-3">
                      {editId === s._id ? (
                        <div className="flex gap-2">
                          <button onClick={() => handleUpdate(s._id)} className="text-xs text-green-600 hover:text-green-800 font-medium px-2 py-1 hover:bg-green-50 rounded">Save</button>
                          <button onClick={() => setEditId(null)} className="text-xs text-slate-500 font-medium px-2 py-1 hover:bg-slate-100 rounded">Cancel</button>
                        </div>
                      ) : (
                        <div className="flex gap-2">
                          <button onClick={() => { setEditId(s._id); setEditQty(s.availableQuantity); }} className="text-xs text-blue-600 hover:text-blue-800 font-medium px-2 py-1 hover:bg-blue-50 rounded">Edit</button>
                          <button onClick={() => handleDelete(s._id)} className="text-xs text-red-600 hover:text-red-800 font-medium px-2 py-1 hover:bg-red-50 rounded">Delete</button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
