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

export default function SalesPage() {
  const [sales, setSales] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [products, setProducts] = useState([]);
  const [message, setMessage] = useState('');
  const [editing, setEditing] = useState(null);
  const [form, setForm] = useState({ invoiceNumber: '', salesDate: '', paymentMethod: '', totalAmountPaid: '', customerNumber: '', productCode: '', quantitySold: '' });

  const fetchSales = async () => {
    const response = await api.get('/sales');
    setSales(response.data);
  };

  const fetchCustomers = async () => {
    const response = await api.get('/customers');
    setCustomers(response.data);
  };

  const fetchProducts = async () => {
    const response = await api.get('/products');
    setProducts(response.data);
  };

  useEffect(() => {
    fetchSales();
    fetchCustomers();
    fetchProducts();
  }, []);

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      if (editing) {
        await api.put(`/sales/${editing}`, {
          invoiceNumber: form.invoiceNumber,
          salesDate: form.salesDate,
          paymentMethod: form.paymentMethod,
          totalAmountPaid: Number(form.totalAmountPaid),
          customerNumber: form.customerNumber,
          productCode: form.productCode,
          quantitySold: Number(form.quantitySold),
        });
        setMessage('Sale updated successfully');
        setEditing(null);
      } else {
        await api.post('/sales', {
          invoiceNumber: form.invoiceNumber,
          salesDate: form.salesDate,
          paymentMethod: form.paymentMethod,
          totalAmountPaid: Number(form.totalAmountPaid),
          customerNumber: form.customerNumber,
          productCode: form.productCode,
          quantitySold: Number(form.quantitySold),
        });
        setMessage('Sale recorded successfully');
      }
      setForm({ invoiceNumber: '', salesDate: '', paymentMethod: '', totalAmountPaid: '', customerNumber: '', productCode: '', quantitySold: '' });
      fetchSales();
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to save sale.');
    }
  };

  const handleEdit = (sale) => {
    setEditing(sale._id);
    setForm({
      invoiceNumber: sale.invoiceNumber,
      salesDate: new Date(sale.salesDate).toISOString().slice(0, 10),
      paymentMethod: sale.paymentMethod,
      totalAmountPaid: sale.totalAmountPaid,
      customerNumber: sale.customerNumber,
      productCode: sale.productCode,
      quantitySold: sale.quantitySold,
    });
    setMessage('Editing sale record. Click save to update.');
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this sale?')) return;
    try {
      await api.delete(`/sales/${id}`);
      setMessage('Sale deleted successfully');
      fetchSales();
      // If the deleted sale was being edited, exit edit mode
      if (editing === id) {
        setEditing(null);
        setForm({ invoiceNumber: '', salesDate: '', paymentMethod: '', totalAmountPaid: '', customerNumber: '', productCode: '', quantitySold: '' });
      }
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to delete sale.');
    }
  };


  return (
    <div className="space-y-6">
      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <h2 className="text-xl font-semibold text-slate-900">Sale Entry</h2>
          <span className="text-sm text-slate-500">Use the form below to add or update sales.</span>
        </div>
        <form onSubmit={handleSubmit} className="mt-5 grid gap-4 sm:grid-cols-2">
          <input
            placeholder="Invoice Number"
            value={form.invoiceNumber}
            required
            onChange={(e) => setForm({ ...form, invoiceNumber: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            type="date"
            value={form.salesDate}
            required
            onChange={(e) => setForm({ ...form, salesDate: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            placeholder="Payment Method"
            value={form.paymentMethod}
            required
            onChange={(e) => setForm({ ...form, paymentMethod: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <input
            type="number"
            min="0"
            step="0.01"
            placeholder="Total Amount Paid"
            value={form.totalAmountPaid}
            required
            onChange={(e) => setForm({ ...form, totalAmountPaid: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <select
            value={form.customerNumber}
            required
            onChange={(e) => setForm({ ...form, customerNumber: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          >
            <option value="">Select Customer</option>
            {customers.map((customer) => (
              <option key={customer._id} value={customer.customerNumber}>
                {customer.customerNumber} - {customer.firstName} {customer.lastName}
              </option>
            ))}
          </select>
          <select
            value={form.productCode}
            required
            onChange={(e) => setForm({ ...form, productCode: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          >
            <option value="">Select Product</option>
            {products.map((product) => (
              <option key={product._id} value={product.productCode}>
                {product.productCode} - {product.productName}
              </option>
            ))}
          </select>
          <input
            type="number"
            min="1"
            placeholder="Quantity Sold"
            value={form.quantitySold}
            required
            onChange={(e) => setForm({ ...form, quantitySold: e.target.value })}
            className="rounded-2xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-500"
          />
          <button className="col-span-full rounded-2xl bg-slate-900 px-5 py-3 text-white hover:bg-slate-800" type="submit">
            {editing ? 'Update Sale' : 'Record Sale'}
          </button>
        </form>
        {message && <p className="mt-4 text-sm text-emerald-600">{message}</p>}
      </section>

      <section className="rounded-3xl bg-white p-6 shadow-[0_10px_25px_rgba(15,23,42,0.10)] shadow-slate-200">
        <h2 className="text-xl font-semibold text-slate-900">Sales Journal</h2>
        <div className="mt-4 overflow-x-auto">
          <table className="w-full min-w-max divide-y divide-slate-200 text-left text-sm text-slate-700">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3">Invoice</th>
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3">Customer</th>
                <th className="px-4 py-3">Product</th>
                <th className="px-4 py-3">Qty</th>
                <th className="px-4 py-3">Amount</th>
                <th className="px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {sales.map((sale) => (
                <tr key={sale._id}>
                  <td className="px-4 py-3">{sale.invoiceNumber}</td>
                  <td className="px-4 py-3">{new Date(sale.salesDate).toLocaleDateString()}</td>
                  <td className="px-4 py-3">{sale.customerNumber}</td>
                  <td className="px-4 py-3">{sale.productCode}</td>
                  <td className="px-4 py-3">{sale.quantitySold}</td>
                  <td className="px-4 py-3">{sale.totalAmountPaid}</td>
                  <td className="px-4 py-3 space-x-2">
                    <button onClick={() => handleEdit(sale)} className="rounded-full bg-amber-500 px-3 py-1 text-sm text-slate-950 hover:bg-amber-400">
                      Edit
                    </button>
                    <button onClick={() => handleDelete(sale._id)} className="rounded-full bg-red-500 px-3 py-1 text-sm text-white hover:bg-red-400">
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
