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

export default function Sales() {
  const [sales, setSales] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState({ customer_id: '', product_id: '', quantity: '' });
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState('');

  const load = () => {
    setLoading(true);
    Promise.all([
      api.get('/sales'),
      api.get('/customers'),
      api.get('/products'),
    ]).then(([s, c, p]) => {
      setSales(s.data);
      setCustomers(c.data);
      setProducts(p.data);
    }).finally(() => setLoading(false));
  };

  useEffect(load, []);

  const openModal = () => { setForm({ customer_id: '', product_id: '', quantity: '' }); setSelectedProduct(null); setError(''); setSuccess(''); setShowModal(true); };
  const closeModal = () => { setShowModal(false); setError(''); };

  const handleChange = e => {
    const { name, value } = e.target;
    setForm(f => ({ ...f, [name]: value }));
    if (name === 'product_id') {
      const prod = products.find(p => p.product_id === parseInt(value));
      setSelectedProduct(prod || null);
    }
  };

  const totalPrice = selectedProduct && form.quantity
    ? (selectedProduct.price * parseInt(form.quantity || 0)).toLocaleString()
    : '0';

  const handleSubmit = async e => {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      await api.post('/sales', form);
      setSuccess(`Sale recorded! Total: ${totalPrice} RWF`);
      setTimeout(() => { closeModal(); load(); }, 1500);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to record sale.');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async id => {
    if (!window.confirm('Delete this sale record? Stock will be restored.')) return;
    try {
      await api.delete(`/sales/${id}`);
      load();
    } catch (err) {
      alert(err.response?.data?.message || 'Failed to delete.');
    }
  };

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Sales</h1>
          <p className="page-subtitle">{sales.length} total transactions</p>
        </div>
        <button className="btn btn-primary" onClick={openModal}>🛒 Record Sale</button>
      </div>

      <div className="card">
        <div className="table-wrapper">
          {loading ? <div className="spinner" /> : sales.length === 0 ? (
            <div className="empty-state">
              <div className="empty-icon">🛒</div>
              <div className="empty-title">No sales recorded yet</div>
            </div>
          ) : (
            <table>
              <thead>
                <tr>
                  <th>Sale ID</th>
                  <th>Customer</th>
                  <th>Product</th>
                  <th>Qty</th>
                  <th>Unit Price</th>
                  <th>Total Price</th>
                  <th>Date</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {sales.map(s => (
                  <tr key={s.sale_id}>
                    <td><span style={{ color: 'var(--text-muted)', fontWeight: 600 }}>#{s.sale_id}</span></td>
                    <td style={{ fontWeight: 600 }}>{s.customer_name}</td>
                    <td>{s.product_name}</td>
                    <td><span style={{ background: 'var(--primary-light)', color: 'var(--primary)', padding: '2px 8px', borderRadius: 12, fontWeight: 700, fontSize: 12 }}>{s.quantity}</span></td>
                    <td>{Number(s.unit_price).toLocaleString()} RWF</td>
                    <td style={{ fontWeight: 700, color: 'var(--success)' }}>{Number(s.total_price).toLocaleString()} RWF</td>
                    <td style={{ color: 'var(--text-muted)' }}>{new Date(s.sale_date).toLocaleDateString()}</td>
                    <td>
                      <button className="btn btn-danger btn-sm" onClick={() => handleDelete(s.sale_id)}>🗑️ Delete</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {showModal && (
        <div className="modal-overlay" onClick={e => e.target === e.currentTarget && closeModal()}>
          <div className="modal" style={{ maxWidth: 480 }}>
            <div className="modal-header">
              <span className="modal-title">🛒 Record New Sale</span>
              <button className="modal-close" onClick={closeModal}>✕</button>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="modal-body">
                {error && <div className="alert alert-error" style={{ marginBottom: 16 }}>⚠️ {error}</div>}
                {success && <div className="alert alert-success" style={{ marginBottom: 16 }}>✅ {success}</div>}

                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  <div className="form-group">
                    <label>Select Customer *</label>
                    <select name="customer_id" value={form.customer_id} onChange={handleChange} required>
                      <option value="">-- Choose Customer --</option>
                      {customers.map(c => <option key={c.customer_id} value={c.customer_id}>{c.full_name} ({c.phone_number})</option>)}
                    </select>
                  </div>

                  <div className="form-group">
                    <label>Select Product *</label>
                    <select name="product_id" value={form.product_id} onChange={handleChange} required>
                      <option value="">-- Choose Product --</option>
                      {products.map(p => (
                        <option key={p.product_id} value={p.product_id} disabled={p.stock === 0}>
                          {p.product_name} — {Number(p.price).toLocaleString()} RWF (Stock: {p.stock})
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="form-group">
                    <label>Quantity *</label>
                    <input type="number" name="quantity" min="1" max={selectedProduct?.stock || 999} placeholder="Enter quantity" value={form.quantity} onChange={handleChange} required />
                    {selectedProduct && <small style={{ color: 'var(--text-muted)', fontSize: 11 }}>Available stock: {selectedProduct.stock}</small>}
                  </div>

                  {/* Auto-calc summary */}
                  {selectedProduct && form.quantity && (
                    <div style={{ background: 'var(--primary-light)', border: '1.5px solid rgba(0,82,255,0.15)', borderRadius: 10, padding: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--primary)', textTransform: 'uppercase', letterSpacing: 0.5 }}>Unit Price</div>
                        <div style={{ fontSize: 17, fontWeight: 800, marginTop: 2 }}>{Number(selectedProduct.price).toLocaleString()} RWF</div>
                      </div>
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--primary)', textTransform: 'uppercase', letterSpacing: 0.5 }}>Total Price</div>
                        <div style={{ fontSize: 17, fontWeight: 800, marginTop: 2, color: 'var(--primary)' }}>{totalPrice} RWF</div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-ghost" onClick={closeModal}>Cancel</button>
                <button type="submit" className="btn btn-success" disabled={saving}>
                  {saving ? '⏳ Processing...' : '✅ Confirm Sale'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
