import { useState, useEffect } from 'react';
import { salesAPI, productsAPI, customersAPI } from '../services/api';

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

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

  const fetchData = async () => {
    try {
      const [salesRes, productsRes, customersRes] = await Promise.all([
        salesAPI.getAll(),
        productsAPI.getAll(),
        customersAPI.getAll(),
      ]);
      setSales(salesRes.data);
      setProducts(productsRes.data);
      setCustomers(customersRes.data);
    } catch {
      setError('Failed to load sales data.');
    } finally {
      setLoading(false);
    }
  };

  const handleProductChange = (productId) => {
    const product = products.find((p) => p.product_id === parseInt(productId, 10));
    setSelectedProduct(product || null);
    setForm({ ...form, product_id: productId });
  };

  const calculateTotal = () => {
    if (!selectedProduct || !form.quantity) return 0;
    return (parseFloat(selectedProduct.price) * parseInt(form.quantity, 10)).toFixed(2);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    try {
      await salesAPI.create({
        customer_id: parseInt(form.customer_id, 10),
        product_id: parseInt(form.product_id, 10),
        quantity: parseInt(form.quantity, 10),
      });
      setSuccess('Sale recorded successfully.');
      setShowModal(false);
      setForm({ customer_id: '', product_id: '', quantity: 1 });
      setSelectedProduct(null);
      fetchData();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to record sale.');
    }
  };

  const formatCurrency = (amount) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

  const formatDate = (date) =>
    new Date(date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });

  return (
    <div>
      <div className="page-header">
        <h1>Sales</h1>
        <button className="btn btn-primary" onClick={() => setShowModal(true)}>
          + Record Sale
        </button>
      </div>

      {error && <div className="alert alert-error">{error}</div>}
      {success && <div className="alert alert-success">{success}</div>}

      <div className="card">
        {loading ? (
          <p className="empty-state">Loading sales...</p>
        ) : sales.length === 0 ? (
          <p className="empty-state">No sales recorded yet.</p>
        ) : (
          <table>
            <thead>
              <tr>
                <th>Sale ID</th>
                <th>Customer</th>
                <th>Product</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Total</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              {sales.map((sale) => (
                <tr key={sale.sale_id}>
                  <td>{sale.sale_id}</td>
                  <td>{sale.customer_name}</td>
                  <td>{sale.product_name}</td>
                  <td>{sale.quantity}</td>
                  <td>{formatCurrency(sale.unit_price)}</td>
                  <td><strong>{formatCurrency(sale.total_price)}</strong></td>
                  <td>{formatDate(sale.sale_date)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {showModal && (
        <div className="modal-overlay" onClick={() => setShowModal(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h2>Record Sale</h2>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Select Customer</label>
                <select
                  value={form.customer_id}
                  onChange={(e) => setForm({ ...form, customer_id: e.target.value })}
                  required
                >
                  <option value="">-- Choose Customer --</option>
                  {customers.map((c) => (
                    <option key={c.customer_id} value={c.customer_id}>
                      {c.fullname} ({c.phone_number})
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label>Select Product</label>
                <select
                  value={form.product_id}
                  onChange={(e) => handleProductChange(e.target.value)}
                  required
                >
                  <option value="">-- Choose Product --</option>
                  {products.map((p) => (
                    <option key={p.product_id} value={p.product_id}>
                      {p.product_name} - {formatCurrency(p.price)} (Stock: {p.quantity})
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label>Quantity</label>
                <input
                  type="number"
                  min="1"
                  max={selectedProduct?.quantity || 999}
                  value={form.quantity}
                  onChange={(e) => setForm({ ...form, quantity: e.target.value })}
                  required
                />
                {selectedProduct && (
                  <small style={{ color: 'var(--text-muted)' }}>
                    Available stock: {selectedProduct.quantity}
                  </small>
                )}
              </div>
              {selectedProduct && (
                <div className="sale-summary card" style={{ background: '#f8fafc', marginBottom: '1rem' }}>
                  <p><strong>Unit Price:</strong> {formatCurrency(selectedProduct.price)}</p>
                  <p><strong>Total:</strong> {formatCurrency(calculateTotal())}</p>
                </div>
              )}
              <div className="modal-actions">
                <button type="button" className="btn btn-outline" onClick={() => setShowModal(false)}>
                  Cancel
                </button>
                <button type="submit" className="btn btn-primary" disabled={!selectedProduct}>
                  Record Sale
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Sales;
