import axios from 'axios';
import { useEffect, useState } from 'react';
import AppLayout from '../components/AppLayout';

function Sales() {
  const [transactions, setTransactions] = useState([]);
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [transactionDate, setTransactionDate] = useState('');
  const [quantityMoved, setQuantityMoved] = useState('');
  const [transactionType, setTransactionType] = useState('Stock In');
  const [productId, setProductId] = useState('');
  const [warehouseId, setWarehouseId] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

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

  const clearForm = () => {
    setTransactionDate('');
    setQuantityMoved('');
    setTransactionType('Stock In');
    setProductId('');
    setWarehouseId('');
    setEditId(null);
  };

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

  const fetchWarehouses = async () => {
    try {
      const res = await axios.get('http://localhost:1000/api/warehouse/getwarehouse', { headers });
      setWarehouses(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  const handleGet = async () => {
    try {
      const res = await axios.get('http://localhost:1000/api/sales/getsales', { headers });
      setTransactions(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    handleGet();
    fetchProducts();
    fetchWarehouses();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:1000/api/sales/updatesales/${editId}`,
          { transactionDate, quantityMoved, transactionType, productId, warehouseId },
          { headers }
        );
        setMessage('Transaction updated successfully');
      } else {
        await axios.post(
          'http://localhost:1000/api/sales/addsales',
          { transactionDate, quantityMoved, transactionType, productId, warehouseId },
          { headers }
        );
        setMessage('Transaction added successfully');
      }
      clearForm();
      handleGet();
    } catch (error) {
      console.log(error);
    }
  };

  const handledelete = async (id) => {
    try {
      await axios.delete(`http://localhost:1000/api/sales/deletesales/${id}`, { headers });
      handleGet();
    } catch (error) {
      console.log(error);
    }
  };

  const handleEdit = (transaction) => {
    setTransactionDate(transaction.transactionDate?.split('T')[0] || '');
    setQuantityMoved(transaction.quantityMoved);
    setTransactionType(transaction.transactionType);
    setProductId(transaction.product?._id || '');
    setWarehouseId(transaction.warehouse?._id || '');
    setEditId(transaction._id);
  };

  return (
    <AppLayout title="Transactions" subtitle="Stock movement">
      <div className="mx-auto max-w-2xl">
        {message && <p className="alert-success mb-4">{message}</p>}

        <form onSubmit={handleSubmit} className="card space-y-4 p-5">
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-600">Transaction date</label>
              <input
                type="date"
                value={transactionDate}
                onChange={(e) => setTransactionDate(e.target.value)}
                className="input-field"
                required
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-600">Quantity moved</label>
              <input
                type="number"
                value={quantityMoved}
                onChange={(e) => setQuantityMoved(e.target.value)}
                className="input-field"
                required
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-600">Type</label>
              <select
                value={transactionType}
                onChange={(e) => setTransactionType(e.target.value)}
                className="input-field"
                required
              >
                <option value="Stock In">Stock In</option>
                <option value="Stock Out">Stock Out</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-600">Product</label>
              <select
                value={productId}
                onChange={(e) => setProductId(e.target.value)}
                className="input-field"
                required
              >
                <option value="">Select product</option>
                {products.map((product) => (
                  <option key={product._id} value={product._id}>
                    {product.productName} ({product.productCode})
                  </option>
                ))}
              </select>
            </div>
            <div className="sm:col-span-2">
              <label className="mb-1 block text-sm font-medium text-slate-600">Warehouse</label>
              <select
                value={warehouseId}
                onChange={(e) => setWarehouseId(e.target.value)}
                className="input-field"
                required
              >
                <option value="">Select warehouse</option>
                {warehouses.map((warehouse) => (
                  <option key={warehouse._id} value={warehouse._id}>
                    {warehouse.warehouseName} ({warehouse.warehouseCode})
                  </option>
                ))}
              </select>
            </div>
          </div>
          <button type="submit" className="btn-primary">
            {editId ? 'Update' : 'Add'} transaction
          </button>
        </form>

        <div className="mt-6 space-y-2">
          {transactions.length === 0 ? (
            <p className="text-sm text-slate-500">No transactions recorded yet.</p>
          ) : (
            transactions.map((transaction) => (
              <div key={transaction._id} className="card p-4 text-sm text-slate-600">
                <p>
                  <span className="font-medium text-slate-800">
                    {new Date(transaction.transactionDate).toLocaleDateString()}
                  </span>{' '}
                  · {transaction.transactionType} · Qty {transaction.quantityMoved}
                </p>
                <p className="mt-1 text-xs">
                  {transaction.product?.productName || 'Unknown'} →{' '}
                  {transaction.warehouse?.warehouseName || 'Unknown'}
                </p>
                <div className="mt-2 flex gap-3 text-xs">
                  <button
                    type="button"
                    onClick={() => handleEdit(transaction)}
                    className="font-medium text-brand-700 hover:text-brand-600"
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    onClick={() => handledelete(transaction._id)}
                    className="font-medium text-red-600 hover:text-red-500"
                  >
                    Delete
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </AppLayout>
  );
}

export default Sales;
