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

function Cars() {
  const { cars, getCars, createCar, updateCar, deleteCar } = useStore()
  const [showForm, setShowForm] = useState(false)
  const [editingId, setEditingId] = useState(null)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [formData, setFormData] = useState({
    plateNumber: '',
    brand: '',
    model: '',
    year: '',
    color: '',
    dailyRate: '',
    image: '',
    status: 'available'
  })

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

  const handleSubmit = async (e) => {
    e.preventDefault()
    const carData = {
      ...formData,
      year: parseInt(formData.year),
      dailyRate: parseFloat(formData.dailyRate)
    }
    if (editingId) {
      await updateCar(editingId, carData)
    } else {
      await createCar(carData)
    }
    resetForm()
  }

  const handleEdit = (car) => {
    setFormData({
      plateNumber: car.plateNumber,
      brand: car.brand,
      model: car.model,
      year: car.year,
      color: car.color,
      dailyRate: car.dailyRate,
      image: car.image || '',
      status: car.status
    })
    setEditingId(car._id)
    setShowForm(true)
  }

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

  const resetForm = () => {
    setFormData({
      plateNumber: '',
      brand: '',
      model: '',
      year: '',
      color: '',
      dailyRate: '',
      image: '',
      status: 'available'
    })
    setEditingId(null)
    setShowForm(false)
  }

  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">Cars</h1>
              <p className="text-sm text-gray-500 mt-0.5">{cars.length} car{cars.length !== 1 ? 's' : ''}</p>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
              <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 sm:w-64"
                />
              </div>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="form-input w-full sm:w-40"
              >
                <option value="">All Status</option>
                <option value="available">Available</option>
                <option value="rented">Rented</option>
                <option value="maintenance">Maintenance</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>
                  Add Car
                </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">
              {editingId ? 'Edit Car' : 'Add New Car'}
            </h3>
            <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="form-group">
                <label className="form-label">Plate Number</label>
                <input
                  type="text"
                  value={formData.plateNumber}
                  onChange={(e) => setFormData({ ...formData, plateNumber: e.target.value })}
                  required
                  className="form-input uppercase"
                  placeholder="ABC-123"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Brand</label>
                <input
                  type="text"
                  value={formData.brand}
                  onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
                  required
                  className="form-input"
                  placeholder="Toyota"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Model</label>
                <input
                  type="text"
                  value={formData.model}
                  onChange={(e) => setFormData({ ...formData, model: e.target.value })}
                  required
                  className="form-input"
                  placeholder="Camry"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Year</label>
                <input
                  type="number"
                  value={formData.year}
                  onChange={(e) => setFormData({ ...formData, year: e.target.value })}
                  required
                  className="form-input"
                  placeholder="2024"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Color</label>
                <input
                  type="text"
                  value={formData.color}
                  onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                  required
                  className="form-input"
                  placeholder="Black"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Daily Rate ($)</label>
                <input
                  type="number"
                  step="0.01"
                  value={formData.dailyRate}
                  onChange={(e) => setFormData({ ...formData, dailyRate: e.target.value })}
                  required
                  className="form-input"
                  placeholder="50.00"
                />
              </div>
              <div className="form-group">
                <label className="form-label">Status</label>
                <select
                  value={formData.status}
                  onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                  className="form-input"
                >
                  <option value="available">Available</option>
                  <option value="rented">Rented</option>
                  <option value="maintenance">Maintenance</option>
                </select>
              </div>
              <div className="form-group md:col-span-2">
                <label className="form-label">Image URL (optional)</label>
                <input
                  type="text"
                  value={formData.image}
                  onChange={(e) => setFormData({ ...formData, image: e.target.value })}
                  className="form-input"
                  placeholder="https://example.com/car.jpg"
                />
              </div>
              <div className="md:col-span-3 flex gap-3 mt-4">
                <button type="submit" className="btn-primary">
                  {editingId ? 'Update Car' : 'Create Car'}
                </button>
                <button type="button" onClick={resetForm} className="btn-secondary">
                  Cancel
                </button>
              </div>
            </form>
          </div>
        )}

        <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>
                  <div className="flex gap-1">
                    <button onClick={() => handleEdit(car)} className="btn-action-edit" title="Edit">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                        />
                      </svg>
                    </button>
                    <button onClick={() => handleDelete(car._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>
                </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="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"
                  />
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 7a4 4 0 100-8 4 4 0 000 8z"
                  />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">No cars found</h3>
              <p className="text-sm text-gray-500">Try adjusting your filters or add a new car.</p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default Cars

