import React, { useEffect, useState } from 'react';
import api from '../services/api';

const initialForm = {
  vehicleName: '',
  plateNumber: '',
  model: '',
  fuelType: 'Petrol',
  capacity: '',
};

export default function Vehicle() {
  const [vehicles, setVehicles] = useState([]);
  const [form, setForm] = useState(initialForm);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');

  const loadVehicles = async () => {
    setLoading(true);
    try {
      const response = await api.get('/vehicles');
      setVehicles(response.data);
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to load vehicles');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setMessage('');
    if (!form.vehicleName || !form.plateNumber || !form.model || !form.fuelType || !form.capacity) {
      setMessage('All fields are required');
      return;
    }

    setSaving(true);
    try {
      await api.post('/vehicles', {
        vehicleName: form.vehicleName,
        plateNumber: form.plateNumber,
        model: form.model,
        fuelType: form.fuelType,
        capacity: Number(form.capacity),
      });
      setForm(initialForm);
      loadVehicles();
      setMessage('Vehicle saved successfully');
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to save vehicle');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="page-header">
        <div>
          <h1 className="page-title">Vehicle Management</h1>
          <p className="text-sm text-gray-500">Register fleet vehicles and review the active fleet list.</p>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.2fr_1fr]">
        <div className="card">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Add New Vehicle</h2>
          {message && <div className="mb-4 rounded-lg bg-blue-50 border border-blue-100 p-4 text-sm text-blue-700">{message}</div>}
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Vehicle Name</label>
              <input value={form.vehicleName} onChange={(e) => setForm({ ...form, vehicleName: e.target.value })} className="input-field" placeholder="e.g. Toyota Hiace" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Plate Number</label>
              <input value={form.plateNumber} onChange={(e) => setForm({ ...form, plateNumber: e.target.value })} className="input-field" placeholder="e.g. RAB 123A" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Model</label>
              <input value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} className="input-field" placeholder="e.g. Hiace" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Fuel Type</label>
              <select value={form.fuelType} onChange={(e) => setForm({ ...form, fuelType: e.target.value })} className="input-field" required>
                <option>Petrol</option>
                <option>Diesel</option>
                <option>Electric</option>
                <option>Hybrid</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Capacity</label>
              <input type="number" value={form.capacity} onChange={(e) => setForm({ ...form, capacity: e.target.value })} className="input-field" placeholder="e.g. 2000" required />
            </div>
            <button type="submit" disabled={saving} className="btn-primary w-full">
              {saving ? 'Saving...' : 'Save Vehicle'}
            </button>
          </form>
        </div>

        <div className="card">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Vehicle List</h2>
          {loading ? (
            <div className="text-center py-10"><div className="animate-spin inline-block h-10 w-10 rounded-full border-b-2 border-blue-600"></div></div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr>
                    <th className="table-header text-left">Vehicle Name</th>
                    <th className="table-header text-left">Plate Number</th>
                    <th className="table-header text-left">Model</th>
                    <th className="table-header text-left">Fuel Type</th>
                    <th className="table-header text-left">Capacity</th>
                  </tr>
                </thead>
                <tbody>
                  {vehicles.map((vehicle) => (
                    <tr key={vehicle._id} className="table-row">
                      <td className="table-cell font-medium">{vehicle.vehicleName}</td>
                      <td className="table-cell">{vehicle.plateNumber}</td>
                      <td className="table-cell">{vehicle.model}</td>
                      <td className="table-cell">{vehicle.fuelType}</td>
                      <td className="table-cell">{vehicle.capacity.toLocaleString()}</td>
                    </tr>
                  ))}
                  {!vehicles.length && (
                    <tr>
                      <td colSpan={5} className="text-center py-10 text-gray-400">No vehicles have been added yet.</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
