import React, { useEffect, useState } from 'react';
import { getSales, createSale, updateSale, deleteSale, getProducts } from '../utils/api';

const emptyForm = { productId: '', soldQuantity: '', soldUnitPrice: '', salesDate: new Date().toISOString().split('T')[0] };

export default function Sales() {
  const [sales, setSales] = useState([]);
  const [products, setProducts] = useState([]);
  const [form, setForm] = useState(emptyForm);
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [showForm, setShowForm] = useState(false);

  const fetchAll = () => {
    setLoading(true);
    Promise.all([getSales(), getProducts()])
      .then(([s, p]) => { setSales(s.data); setProducts(p.data); })
      .catch(console.error)
      .finally(() => setLoading(false));
  };

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

  const handleChange = e => {
    const updated = { ...form, [e.target.name]: e.target.value };
    if (e.target.name === 'productId') {
      const p = products.find(p => p._id === e.target.value);
      if (p) updated.soldUnitPrice = p.unitPrice;
    }
    setForm(updated);
  };

  const handleSubmit = async e => {
    e.preventDefault();
    setError(''); setSuccess('');
    setSubmitting(true);
    try {
      const data = { ...form, soldQuantity: Number(form.soldQuantity), soldUnitPrice: Number(form.soldUnitPrice) };
      if (editId) {
        await updateSale(editId, data);
        setSuccess('Sale updated successfully!');
      } else {
        await createSale(data);
        setSuccess('Sale recorded successfully!');
      }
      setForm(emptyForm); setEditId(null); setShowForm(false);
      fetchAll();
    } catch (err) {
      setError(err.response?.data?.message || 'Operation failed');
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = s => {
    setForm({
      productId: s.productId?._id || '',
      soldQuantity: s.soldQuantity,
      soldUnitPrice: s.soldUnitPrice,
      salesDate: new Date(s.salesDate).toISOString().split('T')[0],
    });
    setEditId(s._id);
    setShowForm(true);
    setError(''); setSuccess('');
  };

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-slate-800">Sales</h1>
          <p className="text-slate-500 text-sm mt-0.5">Record and manage sales transactions</p>
        </div>
        <button
          onClick={() => { setShowForm(!showForm); setEditId(null); setForm(emptyForm); setError(''); setSuccess(''); }}
          className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
        >
          + Record Sale
        </button>
      </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>
      )}

      {showForm && (
        <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
          <h2 className="font-semibold text-slate-800 mb-4">{editId ? 'Edit Sale' : 'Record New Sale'}</h2>
          <form onSubmit={handleSubmit} className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="sm:col-span-2">
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Product *</label>
              <select name="productId" value={form.productId} onChange={handleChange} required
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- Select Product --</option>
                {products.map(p => <option key={p._id} value={p._id}>{p.productName} ({p.category})</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Sold Quantity *</label>
              <input type="number" name="soldQuantity" value={form.soldQuantity} onChange={handleChange} required min="1"
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Unit Price (RWF) *</label>
              <input type="number" name="soldUnitPrice" value={form.soldUnitPrice} onChange={handleChange} required min="0"
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1.5">Sales Date *</label>
              <input type="date" name="salesDate" value={form.salesDate} onChange={handleChange} required
                className="w-full border border-slate-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
            {form.soldQuantity && form.soldUnitPrice && (
              <div className="bg-green-50 rounded-lg px-4 py-2.5 flex items-center">
                <span className="text-sm text-green-700">Total: <strong>RWF {(Number(form.soldQuantity) * Number(form.soldUnitPrice)).toLocaleString()}</strong></span>
              </div>
            )}
            <div className="sm:col-span-2 flex gap-3">
              <button type="submit" disabled={submitting}
                className="bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium px-6 py-2.5 rounded-lg disabled:opacity-60 transition-colors">
                {submitting ? 'Saving...' : editId ? 'Update Sale' : 'Record Sale'}
              </button>
              <button type="button" onClick={() => { setShowForm(false); setForm(emptyForm); setEditId(null); }}
                className="border border-slate-300 text-slate-600 hover:bg-slate-50 text-sm font-medium px-5 py-2.5 rounded-lg transition-colors">
                Cancel
              </button>
            </div>
          </form>
        </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">Sales Records ({sales.length})</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>
        ) : sales.length === 0 ? (
          <div className="text-center py-12 text-slate-400 text-sm">No sales recorded yet.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50">
                <tr>
                  {['#', 'Product', 'Qty Sold', 'Unit Price', 'Total Price', 'Date', '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">
                {sales.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-600">{s.soldQuantity}</td>
                    <td className="px-5 py-3 text-slate-600">RWF {s.soldUnitPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3 font-semibold text-green-700">RWF {s.soldTotalPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3 text-slate-400">{new Date(s.salesDate).toLocaleDateString()}</td>
                    <td className="px-5 py-3">
                      <div className="flex gap-2">
                        <button onClick={() => handleEdit(s)} 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>
  );
}
