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

const API_BASE = 'http://localhost:1000/api/warehouse';

function Warehouse() {
  const [warehouses, setWarehouses] = useState([]);
  const [warehouseCode, setWarehouseCode] = useState('');
  const [warehouseName, setWarehouseName] = useState('');
  const [warehouseLocation, setWarehouseLocation] = useState('');
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [editingId, setEditingId] = useState(null);

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

  const clearForm = () => {
    setWarehouseCode('');
    setWarehouseName('');
    setWarehouseLocation('');
    setEditingId(null);
  };

  const fetchWarehouses = async () => {
    try {
      const response = await axios.get(`${API_BASE}/getwarehouse`, { headers });
      setWarehouses(response.data);
    } catch (err) {
      setError('Failed to load warehouses');
      console.error(err);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setMessage('');
    setError('');

    try {
      if (editingId) {
        await axios.put(
          `${API_BASE}/updatewarehouse/${editingId}`,
          { warehouseCode, warehouseName, warehouseLocation },
          { headers }
        );
        setMessage('Warehouse updated successfully');
      } else {
        await axios.post(
          `${API_BASE}/addwarehouse`,
          { warehouseCode, warehouseName, warehouseLocation },
          { headers }
        );
        setMessage('Warehouse added successfully');
      }
      clearForm();
      fetchWarehouses();
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to save warehouse');
      console.error(err);
    }
  };

  const handleEdit = (warehouse) => {
    setEditingId(warehouse._id);
    setWarehouseCode(warehouse.warehouseCode || '');
    setWarehouseName(warehouse.warehouseName || '');
    setWarehouseLocation(warehouse.warehouseLocation || '');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`${API_BASE}/deletewarehouse/${id}`, { headers });
      setMessage('Warehouse deleted successfully');
      fetchWarehouses();
    } catch (err) {
      setError('Failed to delete warehouse');
      console.error(err);
    }
  };

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

  return (
    <AppLayout title="Warehouse management" subtitle="Locations">
      <div className="mx-auto max-w-6xl space-y-6">
        <div className="card space-y-4 p-5">
          {message && <p className="alert-success">{message}</p>}
          {error && <p className="alert-error">{error}</p>}

          <form onSubmit={handleSubmit} className="space-y-3">
            <h2 className="text-lg font-semibold text-slate-800">
              {editingId ? 'Edit warehouse' : 'Add new warehouse'}
            </h2>
            <div className="grid gap-4 sm:grid-cols-3">
              <input
                type="text"
                placeholder="Warehouse code"
                value={warehouseCode}
                onChange={(e) => setWarehouseCode(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="text"
                placeholder="Warehouse name"
                value={warehouseName}
                onChange={(e) => setWarehouseName(e.target.value)}
                className="input-field"
                required
              />
              <input
                type="text"
                placeholder="Warehouse location"
                value={warehouseLocation}
                onChange={(e) => setWarehouseLocation(e.target.value)}
                className="input-field"
                required
              />
            </div>
            <div className="flex flex-wrap gap-3">
              <button type="submit" className="btn-primary">
                {editingId ? 'Save changes' : 'Add warehouse'}
              </button>
              {editingId && (
                <button type="button" onClick={clearForm} className="btn-secondary">
                  Cancel
                </button>
              )}
            </div>
          </form>
        </div>

        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-800">Warehouses</h2>
          {warehouses.length === 0 ? (
            <p className="mt-4 text-sm text-slate-500">No warehouses available.</p>
          ) : (
            <div className="mt-4 overflow-x-auto">
              <table className="min-w-full divide-y divide-slate-200 text-sm">
                <thead>
                  <tr className="bg-slate-50 text-left text-slate-600">
                    <th className="px-4 py-3">Code</th>
                    <th className="px-4 py-3">Name</th>
                    <th className="px-4 py-3">Location</th>
                    <th className="px-4 py-3">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  {warehouses.map((warehouse) => (
                    <tr key={warehouse._id} className="hover:bg-slate-50">
                      <td className="px-4 py-3">{warehouse.warehouseCode}</td>
                      <td className="px-4 py-3">{warehouse.warehouseName}</td>
                      <td className="px-4 py-3">{warehouse.warehouseLocation}</td>
                      <td className="px-4 py-3 space-x-2">
                        <button
                          type="button"
                          onClick={() => handleEdit(warehouse)}
                          className="btn-secondary"
                        >
                          Edit
                        </button>
                        <button
                          type="button"
                          onClick={() => handleDelete(warehouse._id)}
                          className="btn-danger"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </AppLayout>
  );
}

export default Warehouse;
