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

function BrowseCars() {
  const { cars, getCars, createRental } = useStore()
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(false)
  const [showModal, setShowModal] = useState(false)
  const [selectedCar, setSelectedCar] = useState(null)
  const [returnDate, setReturnDate] = useState('')

  useEffect(() => {
    getCars({ status: 'available', search })
  }, [search])

  const handleRent = async (e) => {
    e.preventDefault()
    if (!selectedCar || !returnDate) return

    setLoading(true)
    const result = await createRental({ carId: selectedCar._id, expectedReturnDate: returnDate })
    setLoading(false)

    if (result.success) {
      // Refresh only the list this page renders (available cars)
      await getCars({ status: 'available', search })

      setShowModal(false)
      setSelectedCar(null)
      setReturnDate('')
    }
  }

  const openRentModal = (car) => {
    setSelectedCar(car)
    setShowModal(true)
    // Set minimum date to tomorrow
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    setReturnDate(tomorrow.toISOString().split('T')[0])
  }

  const closeModal = () => {
    setShowModal(false)
    setSelectedCar(null)
    setReturnDate('')
  }

  const getStatusBadge = (status) => {
    const styles = {
      available: 'bg-green-100 text-green-700',
      rented: 'bg-amber-100 text-amber-700',
      maintenance: 'bg-red-100 text-red-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">Browse Available Cars</h1>
              <p className="text-sm text-gray-500 mt-0.5">{cars.length} car{cars.length !== 1 ? 's' : ''} available</p>
            </div>
            <div className="w-full sm:w-64">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
                <input
                  type="text"
                  placeholder="Search cars..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="form-input pl-9 w-full"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
          {cars.length > 0 ? (
            cars.map((car) => (
              <div key={car._id} className="card p-5 flex flex-col">
                <div className="flex items-start justify-between mb-3">
                  <div className="w-12 h-12 bg-gradient-to-br from-blue-100 to-blue-200 rounded-xl flex items-center justify-center">
                    <svg className="w-6 h-6 text-blue-700" 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>
                  <span className={getStatusBadge(car.status)}>{car.status}</span>
                </div>
                <h3 className="text-base font-semibold text-gray-900">{car.brand} {car.model}</h3>
                <p className="text-sm text-gray-500 mt-1">{car.year} | {car.color}</p>
                <p className="text-sm text-gray-400 mt-1 uppercase">{car.plateNumber}</p>
                <div className="mt-auto pt-4 flex items-center justify-between">
                  <span className="text-lg font-bold text-primary-600">${car.dailyRate}/day</span>
                  <button
                    onClick={() => openRentModal(car)}
                    disabled={loading}
                    className="btn-primary text-sm py-2"
                  >
                    Rent Now
                  </button>
                </div>
              </div>
            ))
          ) : (
            <div className="col-span-full card p-16 text-center">
              <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-8 h-8 text-gray-400" 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>
              <h3 className="text-lg font-semibold text-gray-900">No cars available</h3>
              <p className="text-sm text-gray-500 mt-1">Check back later for available cars</p>
            </div>
          )}
        </div>
      </div>

      {/* Rent Modal */}
      {showModal && selectedCar && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/50" onClick={closeModal} />
          <div className="relative bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Rent Car</h3>
            <div className="mb-4 p-4 bg-gray-50 rounded-lg">
              <p className="font-medium text-gray-900">{selectedCar.brand} {selectedCar.model}</p>
              <p className="text-sm text-gray-500">{selectedCar.year} | {selectedCar.color}</p>
              <p className="text-sm text-gray-500 uppercase">{selectedCar.plateNumber}</p>
              <p className="text-lg font-bold text-primary-600 mt-2">${selectedCar.dailyRate}/day</p>
            </div>
            <form onSubmit={handleRent}>
              <div className="form-group mb-4">
                <label className="form-label">Expected Return Date</label>
                <input
                  type="date"
                  value={returnDate}
                  onChange={(e) => setReturnDate(e.target.value)}
                  required
                  className="form-input"
                  min={new Date().toISOString().split('T')[0]}
                />
              </div>
              <div className="flex gap-3">
                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary flex-1"
                >
                  {loading ? 'Processing...' : 'Confirm Rental'}
                </button>
                <button
                  type="button"
                  onClick={closeModal}
                  className="btn-secondary flex-1"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}

export default BrowseCars