 import { useState, useEffect } from "react";
import axios from "axios";

function ParkingSlot() {
  const [slotNumber, setSlotNumber] = useState('');
  // Fix 1: Set default to 'available' so it matches the dropdown
  const [slotStatus, setSlotStatus] = useState('available'); 
  const [slots, setSlots] = useState([]);

  const getAllSlots = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/parkingSlots');
      // Fix 2: Better "Shield" logic. Checks for array OR nested array.
      const data = Array.isArray(res.data) ? res.data : (res.data.slots || []);
      setSlots(data);
    } catch (error) {
      console.log("Fetch error:", error);
      setSlots([]); 
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:5000/api/parkingSlots', {
        slotNumber,
        slotStatus,
      });
      alert('Slot added successfully');
      setSlotNumber('');
      setSlotStatus('available'); // Reset to default
      getAllSlots();
    } catch (error) {
      alert('Failed to add');
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 p-6">
      <h2 className="text-2xl font-bold text-gray-600 mb-6">Parking Slot</h2>
      
      <form onSubmit={handleSubmit} className="bg-white rounded-xl border border-gray-200 p-6 mb-8 flex flex-col gap-4 max-w-md">
        <div className="flex flex-col gap-2">
          <label className="text-sm font-medium text-gray-600">Slot Number</label>
          <input
            type="text"
            value={slotNumber}
            onChange={(e) => setSlotNumber(e.target.value)}
            className="border border-gray-300 rounded-lg px-4 py-2 text-sm focus:outline-none focus:border-orange-400"
            required
          />

          <label className="text-sm font-medium text-gray-600">Slot Status</label>
          <select
            value={slotStatus}
            onChange={(e) => setSlotStatus(e.target.value)}
            className="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-orange-400"
          >
            <option value="available">Available</option>
            <option value="occupied">Occupied</option>
          </select>
        </div>
        <button
          type="submit"
          className="bg-orange-500 text-white font-medium py-2 rounded-lg hover:bg-orange-600 transition-colors"
        >
          Add Slot
        </button>
      </form>

      <h2 className="text-lg font-semibold text-gray-700 mb-3">Slots List</h2>
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-sm">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-gray-600 text-left">
            <tr>
              <th className="px-4 py-3 font-medium">Slot Number</th>
              <th className="px-4 py-3 font-medium">Status</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {slots.map((slot) => (
              <tr key={slot._id} className="hover:bg-gray-50 transition-colors">
                <td className="px-4 py-3 text-gray-800">{slot.slotNumber}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-1 rounded-full text-xs ${slot.slotStatus === 'available' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                    {slot.slotStatus}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default ParkingSlot;
