import axios from 'axios';
import React, { useEffect, useState } from 'react';

function Sales() {
  const [sales, setSales] = useState([]);
  const [products, setProducts] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [invoiceNumber, setInvoiceNumber] = useState('');
  const [salesDate, setSalesDate] = useState('');
  const [quantitySold, setQuantitySold] = useState('');
  const [totalAmountPaid, setTotalAmountPaid] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('');
  const [productId, setProductId] = useState('');
  const [customerId, setCustomerId] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setInvoiceNumber('');
    setSalesDate('');
    setQuantitySold('');
    setTotalAmountPaid('');
    setPaymentMethod('');
    setProductId('');
    setCustomerId('');
    setEditId(null);
  };

  const loadProducts = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/product/getproduct', { headers });
      setProducts(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const loadCustomers = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/customer/getcustomers', { headers });
      setCustomers(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const loadSales = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/sales/getsales', { headers });
      setSales(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    loadProducts();
    loadCustomers();
    loadSales();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/sales/updatesales/${editId}`,
          {
            invoiceNumber,
            salesDate,
            paymentMethod,
            totalAmountPaid: Number(totalAmountPaid),
            quantitySold: Number(quantitySold),
            productId,
            customerId,
          },
          { headers }
        );
        setMessage('Sale updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/sales/addsales',
          {
            invoiceNumber,
            salesDate,
            paymentMethod,
            totalAmountPaid: Number(totalAmountPaid),
            quantitySold: Number(quantitySold),
            productId,
            customerId,
          },
          { headers }
        );
        setMessage('Sale recorded successfully');
      }
      clearForm();
      loadSales();
    } catch (err) {
      console.error(err);
      setMessage(err.response?.data?.message || 'Unable to save sale');
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5001/api/sales/deletesales/${id}`, { headers });
      loadSales();
    } catch (err) {
      console.error(err);
    }
  };

  const handleEdit = (sale) => {
    setEditId(sale._id);
    setInvoiceNumber(sale.invoiceNumber);
    setSalesDate(sale.salesDate?.substring(0, 10) || '');
    setQuantitySold(sale.quantitySold);
    setTotalAmountPaid(sale.totalAmountPaid);
    setPaymentMethod(sale.paymentMethod);
    setProductId(sale.product_FK?._id || '');
    setCustomerId(sale.customer_FK?._id || '');
  };

  return (
    <div className="max-w-3xl">
      <h1 className="text-xl font-semibold text-brand-900 mb-1">Sales</h1>
      <p className="text-sm text-slate-500 mb-6">Record and manage sales transactions.</p>

      {message && (
        <p className={`mb-4 text-sm ${message.includes('success') ? 'alert-success' : 'alert-error'}`}>
          {message}
        </p>
      )}

      <form onSubmit={handleSubmit} className="card p-5 space-y-4 mb-8">
        <div className="grid gap-3 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Invoice Number</label>
            <input
              type="text"
              value={invoiceNumber}
              onChange={(e) => setInvoiceNumber(e.target.value)}
              className="input"
              placeholder="INV-001"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Sales Date</label>
            <input
              type="date"
              value={salesDate}
              onChange={(e) => setSalesDate(e.target.value)}
              className="input"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Customer</label>
            <select
              value={customerId}
              onChange={(e) => setCustomerId(e.target.value)}
              className="input"
              required
            >
              <option value="">Select customer</option>
              {customers.map((customer) => (
                <option key={customer._id} value={customer._id}>
                  {customer.firstName} {customer.lastName} ({customer.customerNumber})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Product</label>
            <select
              value={productId}
              onChange={(e) => setProductId(e.target.value)}
              className="input"
              required
            >
              <option value="">Select product</option>
              {products.map((product) => (
                <option key={product._id} value={product._id}>
                  {product.productName} ({product.productCode})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Quantity Sold</label>
            <input
              type="number"
              value={quantitySold}
              onChange={(e) => setQuantitySold(e.target.value)}
              className="input"
              min="0"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-600 mb-1">Total Amount Paid</label>
            <input
              type="number"
              value={totalAmountPaid}
              onChange={(e) => setTotalAmountPaid(e.target.value)}
              className="input"
              min="0"
              step="0.01"
              required
            />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-slate-600 mb-1">Payment Method</label>
            <input
              type="text"
              value={paymentMethod}
              onChange={(e) => setPaymentMethod(e.target.value)}
              className="input"
              placeholder="Cash, Mobile Money, Card"
              required
            />
          </div>
        </div>

        <button type="submit" className="btn-primary">
          {editId ? 'Update Sale' : 'Record Sale'}
        </button>
      </form>

      <h2 className="text-sm font-medium text-slate-600 mb-3">Sales history</h2>
      {sales.length === 0 ? (
        <p className="text-sm text-slate-500">No sales recorded yet.</p>
      ) : (
        <div className="space-y-3">
          {sales.map((sale) => (
            <div key={sale._id} className="card p-4">
              <div className="flex flex-wrap justify-between gap-2 text-xs text-slate-500">
                <span>Invoice: {sale.invoiceNumber}</span>
                <span>{new Date(sale.salesDate).toLocaleDateString()}</span>
              </div>
              <p className="font-medium text-brand-900 mt-1">
                {sale.customer_FK?.firstName} {sale.customer_FK?.lastName}
              </p>
              <p className="text-sm text-slate-600">{sale.product_FK?.productName}</p>
              <p className="text-sm text-slate-600">
                Qty {sale.quantitySold} · RWF {sale.totalAmountPaid} · {sale.paymentMethod}
              </p>
              <div className="flex gap-4 mt-3">
                <button type="button" onClick={() => handleEdit(sale)} className="btn-ghost">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(sale._id)} className="btn-danger">
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default Sales;
