import { useEffect, useState } from 'react'
import useStore from '../../store.js'

function MyRentals() {
  const { rentals, getRentals, returnRental } = useStore()
  const [statusFilter, setStatusFilter] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    getRentals({ status: statusFilter })
  }, [statusFilter])

  const handleReturn = async (id) => {
    if (window.confirm('Are you sure you want to return this car?')) {
      setLoading(true)
      await returnRental(id)
      setLoading(false)
    }
  }

  const formatDate = (date) => {
    return new Date(date).toLocaleDateString()
  }

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(amount || 0)
  }

  const getStatusBadge = (status) => {
    const styles = {
      active: 'bg-green-100 text-green-700',
      returned: 'bg-gray-100 text-gray-700'
    }
    return `px-2.5 py-1 rounded-full text-xs font-medium ${styles[status] || 'bg-gray-100 text-gray-700'}`
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white border-b border-gray-200 sticky top-16 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">My Rentals</h1>
              <p className="text-sm text-gray-500 mt-0.5">{rentals.length} rental{rentals.length !== 1 ? 's' : ''}</p>
            </div>
            <div className="w-full sm:w-40">
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="form-input"
              >
                <option value="">All</option>
                <option value="active">Active</option>
                <option value="returned">Returned</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="card overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Car</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Rental Date</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Expected Return</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Amount</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Status</th>
                  <th className="px-5 py-3.5 text-left text-xs font-semibold text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {rentals.length > 0 ? (
                  rentals.map((rental) => (
                    <tr key={rental._id} className="hover:bg-gray-50">
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-9 h-9 bg-blue-50 rounded-lg flex items-center justify-center">
                            <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4M9 17V7m0 10H5a2 2 0 01-2-2V5a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5m-6 0h6" />
                            </svg>
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">{rental.car?.brand} {rental.car?.model}</p>
                            <p className="text-xs text-gray-500">{rental.car?.plateNumber}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600">{formatDate(rental.rentalDate)}</td>
                      <td className="px-5 py-4 text-sm text-gray-600">{formatDate(rental.expectedReturnDate)}</td>
                      <td className="px-5 py-4 font-medium text-gray-900">{formatCurrency(rental.totalAmount)}</td>
                      <td className="px-5 py-4">
                        <span className={getStatusBadge(rental.status)}>{rental.status}</span>
                      </td>
                      <td className="px-5 py-4">
                        {rental.status === 'active' && (
                          <button
                            onClick={() => handleReturn(rental._id)}
                            disabled={loading}
                            className="btn-action-return"
                            title="Return Car"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 16v1a2 2 0 01-2 2H3a2 2 0 01-2-2V7a2 2 0 012-2h2m5 0l3 3m0 0l3-3m-3 3V4" />
                            </svg>
                          </button>
                        )}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={6} className="px-5 py-16 text-center text-gray-500">
                      No rentals found
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}

export default MyRentals