import React, { useState, useEffect } from 'react'
import { supabase } from '../services/supabase.js'

function Drivers() {
  const [drivers, setDrivers] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchDrivers = async () => {
      try {
        const { data, error } = await supabase
          .from('drivers')
          .select('*')
          .order('created_at', { ascending: false })
        
        if (error) throw error
        setDrivers(data || [])
      } catch (error) {
        console.error('Error fetching drivers:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchDrivers()
  }, [])

  if (loading) return <div className="text-center py-8">Loading drivers...</div>

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-semibold">Drivers</h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {drivers.length > 0 ? (
          drivers.map(driver => (
            <DriverCard key={driver.id} driver={driver} />
          ))
        ) : (
          <p className="text-gray-500 col-span-full">No drivers found. Add your first driver!</p>
        )}
      </div>
    </div>
  )
}

function DriverCard({ driver }) {
  return (
    <div className="bg-white rounded-lg shadow p-4 border-l-4 border-blue-500">
      <div className="font-semibold">{driver.name}</div>
      <div className="text-sm text-gray-600">Vehicle: {driver.vehicle_number || 'N/A'}</div>
      <div className="text-sm text-gray-600">Contact: {driver.contact || 'N/A'}</div>
      <div className="text-sm text-gray-600">Total Earnings: ₹{driver.total_earnings?.toLocaleString() || '0'}</div>
      <div className="text-sm text-gray-600">Pending Payments: ₹{driver.pending_payments?.toLocaleString() || '0'}</div>
    </div>
  )
}

export default Drivers