'use client'

import { useEffect, useState } from 'react'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
import { ReservationWizard } from '@/components/reservations/new/ReservationWizard'
import { getReservationWizardCopy } from '@/components/reservations/new/reservationWizard.copy'
import type { Customer, Vehicle } from '@/components/reservations/new/reservationWizard.types'

export default function NewReservationPage() {
  const { language } = useDashboardI18n()
  const copy = getReservationWizardCopy(language)
  const [customers, setCustomers] = useState<Customer[]>([])
  const [vehicles, setVehicles] = useState<Vehicle[]>([])
  const [loading, setLoading] = useState(true)
  const [customerLoadError, setCustomerLoadError] = useState<string | null>(null)
  const [vehicleLoadError, setVehicleLoadError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false

    async function loadData() {
      setLoading(true)
      const [customerResult, vehicleResult] = await Promise.allSettled([
        apiFetch<Customer[]>('/customers?pageSize=100'),
        apiFetch<Vehicle[]>('/vehicles?pageSize=100'),
      ])

      if (cancelled) return

      if (customerResult.status === 'fulfilled') {
        setCustomers(customerResult.value ?? [])
        setCustomerLoadError(null)
      } else {
        setCustomerLoadError(customerResult.reason?.message ?? copy.loadFailed)
      }

      if (vehicleResult.status === 'fulfilled') {
        setVehicles(vehicleResult.value ?? [])
        setVehicleLoadError(null)
      } else {
        setVehicleLoadError(vehicleResult.reason?.message ?? copy.loadFailed)
      }

      setLoading(false)
    }

    void loadData()

    return () => {
      cancelled = true
    }
  }, [copy.loadFailed])

  if (loading) {
    return (
      <div className="card max-w-3xl p-6">
        <p className="text-sm text-slate-500">{copy.loading}</p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {customerLoadError ? <div className="card max-w-3xl p-4 text-sm text-red-700">{customerLoadError}</div> : null}
      {vehicleLoadError ? <div className="card max-w-3xl p-4 text-sm text-red-700">{vehicleLoadError}</div> : null}
      <ReservationWizard customers={customers} vehicles={vehicles} language={language} />
    </div>
  )
}
