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

function Rentals() {
  const { rentals, getRentals, getCars, createRental, returnRental, deleteRental, cars, clients, getClients } = useStore()
  const [showForm, setShowForm] = useState(false)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [formData, setFormData] = useState({
    carId: '',
    clientId: '',
    expectedReturnDate: ''
  })

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

  const handleSubmit = async (e) => {
    e.preventDefault()
    await createRental(formData)
    resetForm()
  }

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

  const handleDelete = async (id) => {
    if (window.confirm('Are you sure you want to delete this rental?')) {
      await deleteRental(id)
    }
  }

  const resetForm = () => {
    setFormData({ carId: '', clientId: '', expectedReturnDate: '' })
    setShowForm(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'}`
  }

  // Get available cars for dropdown
  const availableCars = cars.filter(car => car.status === 'available')

  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">Rentals</h1>
              <p className="text-sm text-gray-500 mt-0.5">{rentals.length} rental{rentals.length !== 1 ? 's' : ''}</p>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="form-input w-full sm:w-40"
              >
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="returned">Returned</option>
              </select>
              {!showForm && (
                <button onClick={() => setShowForm(true)} className="btn-primary flex items-center gap-2 w-fit">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                  </svg>
                  Create Rental
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {showForm && (
          <div className="card mb-6 p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Create New Rental</h3>
            <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="form-group">
                <label className="form-label">Select Car</label>
                <select
                  value={formData.carId}
                  onChange={(e) => setFormData({ ...formData, carId: e.target.value })}
                  required
                  className="form-input"
                >
                  <option value="">Select a car</option>
                  {availableCars.map((car) => (
                    <option key={car._id} value={car._id}>
                      {car.plateNumber} - {car.brand} {car.model} (${car.dailyRate}/day)
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">Select Client</label>
                <select
                  value={formData.clientId}
                  onChange={(e) => setFormData({ ...formData, clientId: e.target.value })}
                  required
                  className="form-input"
                >
                  <option value="">Select a client</option>
                  {clients.map((client) => (
                    <option key={client._id} value={client._id}>
                      {client.fullName} ({client.email})
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">Expected Return Date</label>
                <input
                  type="date"
                  value={formData.expectedReturnDate}
                  onChange={(e) => setFormData({ ...formData, expectedReturnDate: e.target.value })}
                  required
                  className="form-input"
                  min={new Date().toISOString().split('T')[0]}
                />
              </div>
              <div className="md:col-span-2 flex gap-3 mt-4">
                <button type="submit" className="btn-primary">
                  Create Rental
                </button>
                <button type="button" onClick={resetForm} className="btn-secondary">
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}

        <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">Client</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">
                        <p className="font-medium text-gray-900">{rental.client?.fullName}</p>
                        <p className="text-xs text-gray-500">{rental.client?.email}</p>
                      </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">
                        <div className="flex items-center gap-2">
                          {rental.status === 'active' && (
                            <button
                              onClick={() => handleReturn(rental._id)}
                              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>
                          )}
                          <button
                            onClick={() => handleDelete(rental._id)}
                            className="btn-action-delete"
                            title="Delete"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={7} className="px-5 py-16 text-center text-gray-500">
                      No rentals found
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Rentals