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

const initialForm = {
  productCode: '',
  warehouseCode: '',
  transactionDate: '',
  quantityMoved: '',
  transactionType: 'IN',
};

export default function Transactions() {
  const [form, setForm] = useState(initialForm);
  const [transactions, setTransactions] = useState([]);
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    try {
      const [txRes, prodRes, whRes] = await Promise.all([
        API.get('/transactions'),
        API.get('/products'),
        API.get('/warehouses'),
      ]);
      setTransactions(txRes.data);
      setProducts(prodRes.data);
      setWarehouses(whRes.data);
    } catch {
      setMessage({ type: 'error', text: 'Failed to load data.' });
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage({ type: '', text: '' });

    const payload = {
      ...form,
      quantityMoved: parseInt(form.quantityMoved, 10),
    };

    try {
      if (editingId) {
        await API.put(`/transactions/${editingId}`, payload);
        setMessage({ type: 'success', text: 'Transaction updated successfully!' });
        setEditingId(null);
      } else {
        await API.post('/transactions', payload);
        setMessage({ type: 'success', text: 'Transaction recorded successfully!' });
      }
      setForm(initialForm);
      fetchData();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Operation failed.' });
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (tx) => {
    setEditingId(tx.transactionId);
    setForm({
      productCode: tx.productCode,
      warehouseCode: tx.warehouseCode,
      transactionDate: tx.transactionDate?.split('T')[0] || tx.transactionDate,
      quantityMoved: tx.quantityMoved,
      transactionType: tx.transactionType,
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this transaction?')) return;

    try {
      await API.delete(`/transactions/${id}`);
      setMessage({ type: 'success', text: 'Transaction deleted successfully!' });
      fetchData();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Delete failed.' });
    }
  };

  const cancelEdit = () => {
    setEditingId(null);
    setForm(initialForm);
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-ink-900">Stock Transactions</h2>
        <p className="text-ink-500 mt-1">Create, read, update and delete stock movements</p>
      </div>

      {message.text && (
        <div className={`mb-6 p-4 rounded-lg text-sm ${
          message.type === 'success' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200'
        }`}>
          {message.text}
        </div>
      )}

      <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6 mb-8">
        <h3 className="text-lg font-semibold mb-4">
          {editingId ? 'Edit Transaction' : 'New Transaction'}
        </h3>
        <form onSubmit={handleSubmit} className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-ink-700 mb-1">Product</label>
            <select name="productCode" value={form.productCode} onChange={handleChange} required
              className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
              <option value="">Select product</option>
              {products.map((p) => (
                <option key={p.productCode} value={p.productCode}>{p.productCode} - {p.productName}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-ink-700 mb-1">Warehouse</label>
            <select name="warehouseCode" value={form.warehouseCode} onChange={handleChange} required
              className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
              <option value="">Select warehouse</option>
              {warehouses.map((w) => (
                <option key={w.warehouseCode} value={w.warehouseCode}>{w.warehouseCode} - {w.warehouseName}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-ink-700 mb-1">Transaction Date</label>
            <input name="transactionDate" type="date" value={form.transactionDate} onChange={handleChange} required
              className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
          </div>
          <div>
            <label className="block text-sm font-medium text-ink-700 mb-1">Quantity Moved</label>
            <input name="quantityMoved" type="number" min="1" value={form.quantityMoved} onChange={handleChange} required
              className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" />
          </div>
          <div>
            <label className="block text-sm font-medium text-ink-700 mb-1">Transaction Type</label>
            <select name="transactionType" value={form.transactionType} onChange={handleChange} required
              className="w-full px-3 py-2 border border-ink-200 rounded-lg bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
              <option value="IN">Stock IN</option>
              <option value="OUT">Stock OUT</option>
            </select>
          </div>
          <div className="flex items-end gap-2 sm:col-span-2 lg:col-span-1">
            <button type="submit" disabled={loading}
              className="flex-1 py-2.5 bg-primary-600 text-white font-semibold rounded-lg hover:bg-primary-700 shadow-sm shadow-primary-900/20 disabled:opacity-50">
              {loading ? 'Saving...' : editingId ? 'Update' : 'Add Transaction'}
            </button>
            {editingId && (
              <button type="button" onClick={cancelEdit}
                className="px-4 py-2.5 border border-ink-200 text-ink-700 rounded-lg hover:bg-ink-100">
                Cancel
              </button>
            )}
          </div>
        </form>
      </div>

      <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6 overflow-hidden">
        <h3 className="text-lg font-semibold mb-4">Transaction History</h3>
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="bg-ink-100">
              <tr>
                <th className="px-3 py-2 text-left font-medium text-ink-700">ID</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Date</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Product</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Warehouse</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Qty</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Type</th>
                <th className="px-3 py-2 text-left font-medium text-ink-700">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-ink-100">
              {transactions.map((tx) => (
                <tr key={tx.transactionId} className="hover:bg-primary-50/60">
                  <td className="px-3 py-2">{tx.transactionId}</td>
                  <td className="px-3 py-2">{tx.transactionDate?.split('T')[0] || tx.transactionDate}</td>
                  <td className="px-3 py-2">{tx.productName}</td>
                  <td className="px-3 py-2">{tx.warehouseName}</td>
                  <td className="px-3 py-2">{tx.quantityMoved}</td>
                  <td className="px-3 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                      tx.transactionType === 'IN' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'
                    }`}>
                      {tx.transactionType}
                    </span>
                  </td>
                  <td className="px-3 py-2">
                    <div className="flex gap-2">
                      <button onClick={() => handleEdit(tx)}
                        className="text-primary-600 hover:underline text-xs font-medium">Edit</button>
                      <button onClick={() => handleDelete(tx.transactionId)}
                        className="text-rose-600 hover:underline text-xs font-medium">Delete</button>
                    </div>
                  </td>
                </tr>
              ))}
              {transactions.length === 0 && (
                <tr><td colSpan="7" className="px-3 py-8 text-center text-ink-500">No transactions yet</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
