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

const initialForm = {
  vehicle: '',
  tripDate: new Date().toISOString().slice(0, 10),
  destination: '',
  fuelConsumed: '',
  tripCost: '',
};

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [vehicleRes, tripRes] = await Promise.all([api.get('/vehicles'), api.get('/trips')]);
      setVehicles(vehicleRes.data);
      setTrips(tripRes.data);
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to load trips');
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setMessage('');
    if (!form.vehicle || !form.tripDate || !form.destination || form.fuelConsumed === '' || form.tripCost === '') {
      setMessage('All trip fields are required');
      return;
    }

    setSaving(true);
    try {
      await api.post('/trips', {
        vehicle: form.vehicle,
        tripDate: form.tripDate,
        destination: form.destination,
        fuelConsumed: Number(form.fuelConsumed),
        tripCost: Number(form.tripCost),
      });
      setForm(initialForm);
      loadData();
      setMessage('Trip saved successfully');
    } catch (error) {
      setMessage(error.response?.data?.message || 'Unable to save trip');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="page-header">
        <div>
          <h1 className="page-title">Trip Management</h1>
          <p className="text-sm text-gray-500">Log daily trips and review your fleet's travel history.</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 Trip</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</label>
              <select value={form.vehicle} onChange={(e) => setForm({ ...form, vehicle: e.target.value })} className="input-field" required>
                <option value="">Select a vehicle</option>
                {vehicles.map((vehicle) => (
                  <option key={vehicle._id} value={vehicle._id}>
                    {vehicle.vehicleName} — {vehicle.plateNumber}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Trip Date</label>
              <input type="date" value={form.tripDate} onChange={(e) => setForm({ ...form, tripDate: e.target.value })} className="input-field" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Destination</label>
              <input value={form.destination} onChange={(e) => setForm({ ...form, destination: e.target.value })} className="input-field" placeholder="Destination" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Fuel Consumed</label>
              <input type="number" value={form.fuelConsumed} onChange={(e) => setForm({ ...form, fuelConsumed: e.target.value })} className="input-field" placeholder="Liters" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Trip Cost</label>
              <input type="number" value={form.tripCost} onChange={(e) => setForm({ ...form, tripCost: e.target.value })} className="input-field" placeholder="Amount" required />
            </div>
            <button type="submit" disabled={saving} className="btn-primary w-full">
              {saving ? 'Saving...' : 'Save Trip'}
            </button>
          </form>
        </div>

        <div className="card">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Trip 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</th>
                    <th className="table-header text-left">Trip Date</th>
                    <th className="table-header text-left">Destination</th>
                    <th className="table-header text-left">Fuel Consumed</th>
                    <th className="table-header text-left">Trip Cost</th>
                  </tr>
                </thead>
                <tbody>
                  {trips.map((trip) => (
                    <tr key={trip._id} className="table-row">
                      <td className="table-cell font-medium">{trip.vehicle?.vehicleName || 'Unknown'}</td>
                      <td className="table-cell">{new Date(trip.tripDate).toLocaleDateString()}</td>
                      <td className="table-cell">{trip.destination}</td>
                      <td className="table-cell">{trip.fuelConsumed}</td>
                      <td className="table-cell">{trip.tripCost}</td>
                    </tr>
                  ))}
                  {!trips.length && (
                    <tr>
                      <td colSpan={5} className="text-center py-10 text-gray-400">No trips recorded yet.</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
