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

const today = new Date().toISOString().slice(0, 10);

export default function Reports() {
  const [date, setDate] = useState(today);
  const [dailyTrips, setDailyTrips] = useState([]);
  const [fleetStatus, setFleetStatus] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const loadReports = async (selectedDate) => {
    setLoading(true);
    setError('');
    try {
      const [tripRes, fleetRes] = await Promise.all([
        api.get('/reports/daily-trips', { params: { date: selectedDate } }),
        api.get('/reports/fleet-status', { params: { date: selectedDate } }),
      ]);
      setDailyTrips(tripRes.data);
      setFleetStatus(fleetRes.data);
    } catch (err) {
      setError(err.response?.data?.message || 'Unable to load reports');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadReports(date);
  }, [date]);

  return (
    <div className="space-y-6">
      <div className="page-header">
        <div>
          <h1 className="page-title">Reports</h1>
          <p className="text-sm text-gray-500">View daily trip and fleet status reports for your fleet.</p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <label className="text-sm text-gray-700">
            Filter date
            <input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="input-field mt-2 sm:mt-0" />
          </label>
          <button type="button" onClick={() => loadReports(date)} className="btn-secondary">
            Refresh
          </button>
        </div>
      </div>

      {error && <div className="rounded-lg bg-red-50 border border-red-100 p-4 text-sm text-red-700">{error}</div>}

      {loading ? (
        <div className="text-center py-16">
          <div className="animate-spin inline-block h-12 w-12 rounded-full border-b-2 border-blue-600"></div>
        </div>
      ) : (
        <div className="space-y-6">
          <div className="card">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">Daily Trip Report</h2>
            <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">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>
                  {dailyTrips.map((trip, index) => (
                    <tr key={`${trip.vehicleName}-${index}`} className="table-row">
                      <td className="table-cell font-medium">{trip.vehicleName}</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>
                  ))}
                  {!dailyTrips.length && (
                    <tr>
                      <td colSpan={5} className="text-center py-10 text-gray-400">No trip records found for this date.</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          <div className="card">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">Daily Fleet Status Report</h2>
            <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">Fuel Consumed</th>
                    <th className="table-header text-left">Maintenance Status</th>
                    <th className="table-header text-left">Vehicle Availability</th>
                  </tr>
                </thead>
                <tbody>
                  {fleetStatus.map((item) => (
                    <tr key={item.vehicleName} className="table-row">
                      <td className="table-cell font-medium">{item.vehicleName}</td>
                      <td className="table-cell">{item.fuelConsumed}</td>
                      <td className="table-cell">{item.maintenanceStatus}</td>
                      <td className="table-cell">{item.availability}</td>
                    </tr>
                  ))}
                  {!fleetStatus.length && (
                    <tr>
                      <td colSpan={4} className="text-center py-10 text-gray-400">No fleet status records available for this date.</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
