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

const initialForm = {
  warehouseCode: '',
  warehouseName: '',
  warehouseLocation: '',
};

export default function Warehouses() {
  const [form, setForm] = useState(initialForm);
  const [warehouses, setWarehouses] = useState([]);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);

  const fetchWarehouses = async () => {
    try {
      const { data } = await API.get('/warehouses');
      setWarehouses(data);
    } catch {
      setMessage({ type: 'error', text: 'Failed to load warehouses.' });
    }
  };

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

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

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

    try {
      await API.post('/warehouses', form);
      setMessage({ type: 'success', text: 'Warehouse added successfully!' });
      setForm(initialForm);
      fetchWarehouses();
    } catch (err) {
      setMessage({ type: 'error', text: err.response?.data?.message || 'Failed to add warehouse.' });
    } finally {
      setLoading(false);
    }
  };

  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">Warehouse Management</h2>
        <p className="text-ink-500 mt-1">Add new warehouses (Insert only)</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="grid lg:grid-cols-2 gap-8">
        <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6">
          <h3 className="text-lg font-semibold mb-4">Add New Warehouse</h3>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-ink-700 mb-1">Warehouse Code</label>
              <input 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" />
            </div>
            <div>
              <label className="block text-sm font-medium text-ink-700 mb-1">Warehouse Name</label>
              <input name="warehouseName" value={form.warehouseName} 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">Warehouse Location</label>
              <input name="warehouseLocation" value={form.warehouseLocation} 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>
            <button type="submit" disabled={loading}
              className="w-full 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...' : 'Add Warehouse'}
            </button>
          </form>
        </div>

        <div className="bg-white/95 rounded-xl shadow-sm shadow-ink-900/5 border border-ink-200 p-6">
          <h3 className="text-lg font-semibold mb-4">Warehouse List</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">Code</th>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Name</th>
                  <th className="px-3 py-2 text-left font-medium text-ink-700">Location</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-ink-100">
                {warehouses.map((w) => (
                  <tr key={w.warehouseCode} className="hover:bg-primary-50/60">
                    <td className="px-3 py-2 font-medium">{w.warehouseCode}</td>
                    <td className="px-3 py-2">{w.warehouseName}</td>
                    <td className="px-3 py-2">{w.warehouseLocation}</td>
                  </tr>
                ))}
                {warehouses.length === 0 && (
                  <tr><td colSpan="3" className="px-3 py-8 text-center text-ink-500">No warehouses yet</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
