import { useState, useEffect } from 'react';
import {
  createTransaction,
  getAllTransactions,
  updateTransaction,
  deleteTransaction,
  getAllProducts,
  getAllWarehouses,
} from '../services/apiService';

const TransactionsPage = () => {
  const [formData, setFormData] = useState({
    productId: '',
    warehouseId: '',
    transactionDate: new Date().toISOString().split('T')[0],
    quantityMoved: '',
    transactionType: 'Stock In',
  });
  const [transactions, setTransactions] = useState([]);
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);
  const [editingId, setEditingId] = useState(null);

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

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: name === 'quantityMoved' ? parseFloat(value) || '' : value,
    }));
  };

  const resetForm = () => {
    setFormData({
      productId: '',
      warehouseId: '',
      transactionDate: new Date().toISOString().split('T')[0],
      quantityMoved: '',
      transactionType: 'Stock In',
    });
    setEditingId(null);
  };

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

    try {
      if (editingId) {
        await updateTransaction(editingId, formData);
        setSuccess('Transaction updated successfully!');
      } else {
        await createTransaction(formData);
        setSuccess('Transaction created successfully!');
      }
      resetForm();
      fetchTransactions();
      fetchProducts();
    } catch (err) {
      setError(err.response?.data?.message || 'Error saving transaction');
    } finally {
      setLoading(false);
    }
  };

  const fetchProducts = async () => {
    try {
      const response = await getAllProducts();
      setProducts(response.data);
    } catch (err) {
      console.error('Error fetching products:', err);
    }
  };

  const fetchWarehouses = async () => {
    try {
      const response = await getAllWarehouses();
      setWarehouses(response.data);
    } catch (err) {
      console.error('Error fetching warehouses:', err);
    }
  };

  const fetchTransactions = async () => {
    try {
      const response = await getAllTransactions();
      setTransactions(response.data);
    } catch (err) {
      console.error('Error fetching transactions:', err);
    }
  };

  const handleEdit = (transaction) => {
    setFormData({
      productId: transaction.productId._id,
      warehouseId: transaction.warehouseId._id,
      transactionDate: transaction.transactionDate.split('T')[0],
      quantityMoved: transaction.quantityMoved,
      transactionType: transaction.transactionType,
    });
    setEditingId(transaction._id);
  };

  const handleDelete = async (id) => {
    if (window.confirm('Are you sure you want to delete this transaction?')) {
      try {
        await deleteTransaction(id);
        setSuccess('Transaction deleted successfully!');
        fetchTransactions();
        fetchProducts();
      } catch (err) {
        setError(err.response?.data?.message || 'Error deleting transaction');
      }
    }
  };

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6">
      <h2 className="text-2xl sm:text-3xl font-bold mb-6 text-gray-800">Stock Transactions</h2>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-1">
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-xl font-bold mb-4 text-gray-800">
              {editingId ? 'Edit Transaction' : 'Add New Transaction'}
            </h3>

            {error && (
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
            )}
            {success && (
              <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">{success}</div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Product</label>
                <select name="productId" value={formData.productId} onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                  <option value="">Select Product</option>
                  {products.map((p) => (
                    <option key={p._id} value={p._id}>
                      {p.productName} (Stock: {p.quantityInStock})
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Warehouse</label>
                <select name="warehouseId" value={formData.warehouseId} onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                  <option value="">Select Warehouse</option>
                  {warehouses.map((w) => (
                    <option key={w._id} value={w._id}>
                      {w.warehouseName} — {w.warehouseLocation}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Transaction Date</label>
                <input type="date" name="transactionDate" value={formData.transactionDate} onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required />
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Transaction Type</label>
                <select name="transactionType" value={formData.transactionType} onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
                  <option value="Stock In">Stock In</option>
                  <option value="Stock Out">Stock Out</option>
                </select>
              </div>
              <div>
                <label className="block text-gray-700 text-sm font-bold mb-2">Quantity Moved</label>
                <input type="number" name="quantityMoved" value={formData.quantityMoved} onChange={handleChange} min="1"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required />
              </div>
              <button type="submit" disabled={loading}
                className="w-full bg-blue-600 text-white font-bold py-2 rounded-lg hover:bg-blue-700 transition disabled:opacity-50">
                {loading ? 'Saving...' : editingId ? 'Update Transaction' : 'Create Transaction'}
              </button>
              {editingId && (
                <button type="button" onClick={resetForm}
                  className="w-full bg-gray-600 text-white font-bold py-2 rounded-lg hover:bg-gray-700 transition mt-2">
                  Cancel
                </button>
              )}
            </form>
          </div>
        </div>

        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-xl font-bold mb-4 text-gray-800">Transaction Records</h3>

            {transactions.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full border-collapse text-sm">
                  <thead>
                    <tr className="bg-gray-200">
                      <th className="border px-2 py-2 text-left">Date</th>
                      <th className="border px-2 py-2 text-left">Product</th>
                      <th className="border px-2 py-2 text-left">Warehouse</th>
                      <th className="border px-2 py-2 text-left">Type</th>
                      <th className="border px-2 py-2 text-right">Qty</th>
                      <th className="border px-2 py-2">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {transactions.map((t) => (
                      <tr key={t._id} className="hover:bg-gray-100">
                        <td className="border px-2 py-2">{new Date(t.transactionDate).toLocaleDateString()}</td>
                        <td className="border px-2 py-2">{t.productId?.productName}</td>
                        <td className="border px-2 py-2">{t.warehouseId?.warehouseName}</td>
                        <td className="border px-2 py-2">
                          <span className={`px-2 py-1 rounded text-xs font-bold ${
                            t.transactionType === 'Stock In' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                          }`}>
                            {t.transactionType}
                          </span>
                        </td>
                        <td className="border px-2 py-2 text-right">{t.quantityMoved}</td>
                        <td className="border px-2 py-2 whitespace-nowrap">
                          <button onClick={() => handleEdit(t)}
                            className="bg-yellow-500 text-white px-2 py-1 rounded text-xs hover:bg-yellow-600 mr-1">
                            Edit
                          </button>
                          <button onClick={() => handleDelete(t._id)}
                            className="bg-red-600 text-white px-2 py-1 rounded text-xs hover:bg-red-700">
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-gray-600">No transactions found. Add products and warehouses first.</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TransactionsPage;
