import { useEffect, useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import useSalesStore from '../../store/saleStore';
import useProductStore from '../../store/productStore';
import useCustomerStore from '../../store/customerStore';

const SalesPage = () => {
  const { sales, fetchSales, addSale, deleteSale } = useSalesStore();
  const { products, fetchProducts } = useProductStore();
  const { customers, fetchCustomers } = useCustomerStore();
  const [showModal, setShowModal] = useState(false);
  const [formData, setFormData] = useState({
    product_id: '', customer_id: '', quantity: '', unit_price: ''
  });

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

  const openModal = () => {
    setFormData({ product_id: '', customer_id: '', quantity: '', unit_price: '' });
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
  };

  const handleProductChange = (productId) => {
    const product = products.find((p) => p.product_id === parseInt(productId));
    setFormData({
      ...formData,
      product_id: productId,
      unit_price: product ? product.price : '',
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const product = products.find((p) => p.product_id === parseInt(formData.product_id));
    const customer = customers.find((c) => c.customer_id === parseInt(formData.customer_id));
    const quantity = parseInt(formData.quantity);
    const unit_price = parseFloat(formData.unit_price);

    const saleData = {
      customer_name: customer ? customer.full_name : 'Walk-in',
      product_name: product ? product.product_name : '',
      quantity: quantity,
      unit_price: unit_price,
      total_price: quantity * unit_price,
    };

    await addSale(saleData);
    closeModal();
    fetchSales();
  };

  const handleDelete = async (sale_id) => {
    if (window.confirm('Delete this sale?')) {
      await deleteSale(sale_id);
      fetchSales();
    }
  };

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold text-gray-800">Sales</h1>
        <button onClick={openModal} className="bg-green-500 text-white px-4 py-2 rounded-lg flex items-center gap-2">
          <Plus className="w-4 h-4" /> New Sale
        </button>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-100">
            <tr>
              <th className="px-4 py-3 text-left">Product</th>
              <th className="px-4 py-3 text-left">Customer</th>
              <th className="px-4 py-3 text-left">Quantity</th>
              <th className="px-4 py-3 text-left">Total</th>
              <th className="px-4 py-3 text-center">Actions</th>
            </tr>
          </thead>
          <tbody>
            {sales.map((sale) => (
              <tr key={sale.sale_id} className="border-t hover:bg-gray-50">
                <td className="px-4 py-3">{sale.product_name}</td>
                <td className="px-4 py-3">{sale.customer_name}</td>
                <td className="px-4 py-3">{sale.quantity}</td>
                <td className="px-4 py-3">${Number(sale.total_price || 0).toLocaleString()}</td>
                <td className="px-4 py-3 text-center">
                  <button onClick={() => handleDelete(sale.sale_id)} className="text-red-500">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </td>
              </tr>
            ))}
            {sales.length === 0 && (
              <tr><td colSpan="5" className="px-4 py-8 text-center text-gray-500">No sales</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
          <div className="bg-white rounded-lg p-6 w-96">
            <h2 className="text-xl font-bold mb-4">New Sale</h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-sm font-medium">Product</label>
                <select value={formData.product_id} onChange={(e) => handleProductChange(e.target.value)} className="w-full border rounded px-3 py-2" required>
                  <option value="">Select product</option>
                  {products.map((p) => (
                    <option key={p.product_id} value={p.product_id}>{p.product_name} (${p.price})</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium">Customer</label>
                <select value={formData.customer_id} onChange={(e) => setFormData({ ...formData, customer_id: e.target.value })} className="w-full border rounded px-3 py-2">
                  <option value="">Walk-in Customer</option>
                  {customers.map((c) => (
                    <option key={c.customer_id} value={c.customer_id}>{c.full_name}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium">Quantity</label>
                  <input type="number" value={formData.quantity} onChange={(e) => setFormData({ ...formData, quantity: e.target.value })} className="w-full border rounded px-3 py-2" required />
                </div>
                <div>
                  <label className="block text-sm font-medium">Unit Price ($)</label>
                  <input type="number" step="0.01" value={formData.unit_price} onChange={(e) => setFormData({ ...formData, unit_price: e.target.value })} className="w-full border rounded px-3 py-2" required />
                </div>
              </div>
              <div className="flex justify-end gap-2 mt-6">
                <button type="button" onClick={closeModal} className="px-4 py-2 border rounded">Cancel</button>
                <button type="submit" className="px-4 py-2 bg-green-500 text-white rounded">Record Sale</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default SalesPage;