'use client'

import { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { motion, AnimatePresence } from 'framer-motion'
import { Box, Crown, Warehouse, ChevronLeft, ChevronRight, Check } from 'lucide-react'
import PageTransition from '@/components/PageTransition'
import { services, generateTimeSlots, type Service, type TimeSlot } from '@/lib/mock-data'
import { formatPrice } from '@/lib/utils'

const serviceIcons: Record<string, React.ReactNode> = {
  Box: <Box className="w-6 h-6" />,
  Crown: <Crown className="w-6 h-6" />,
  Warehouse: <Warehouse className="w-6 h-6" />,
}

function getDays(n = 7): Date[] {
  return Array.from({ length: n }, (_, i) => {
    const d = new Date()
    d.setDate(d.getDate() + i)
    return d
  })
}

const DAY_NAMES = ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam']
const MONTH_NAMES = ['jan', 'fév', 'mar', 'avr', 'mai', 'jun', 'jul', 'aoû', 'sep', 'oct', 'nov', 'déc']

function formatShortDate(d: Date): string {
  return `${d.getDate()} ${MONTH_NAMES[d.getMonth()]}`
}

// Step indicator
function ProgressBar({ step }: { step: number }) {
  const steps = ['Espace', 'Créneau', 'Récap']
  return (
    <div className="flex items-center justify-center gap-0 mb-8">
      {steps.map((label, i) => (
        <div key={i} className="flex items-center">
          <div className="flex flex-col items-center">
            <motion.div
              animate={{
                backgroundColor: i <= step ? '#4f46e5' : '#e5e7eb',
                scale: i === step ? 1.15 : 1,
              }}
              transition={{ duration: 0.3 }}
              className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold"
              style={{ color: i <= step ? 'white' : '#9ca3af' }}
            >
              {i < step ? <Check className="w-4 h-4" /> : i + 1}
            </motion.div>
            <span
              className={`text-xs mt-1 font-medium ${
                i <= step ? 'text-brand-600' : 'text-gray-400'
              }`}
            >
              {label}
            </span>
          </div>
          {i < steps.length - 1 && (
            <motion.div
              animate={{ backgroundColor: i < step ? '#4f46e5' : '#e5e7eb' }}
              transition={{ duration: 0.3 }}
              className="h-0.5 w-12 md:w-20 mx-1 mb-5 rounded"
            />
          )}
        </div>
      ))}
    </div>
  )
}

const slideVariants = {
  enter: (dir: number) => ({
    x: dir > 0 ? 60 : -60,
    opacity: 0,
  }),
  center: { x: 0, opacity: 1 },
  exit: (dir: number) => ({
    x: dir > 0 ? -60 : 60,
    opacity: 0,
  }),
}

function BookingContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const preselectedService = searchParams.get('service')

  const [step, setStep] = useState(0)
  const [direction, setDirection] = useState(1)
  const [selectedService, setSelectedService] = useState<Service | null>(
    preselectedService ? services.find((s) => s.id === preselectedService) ?? null : null
  )
  const [selectedDay, setSelectedDay] = useState<Date>(new Date())
  const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([])
  const [selectedSlot, setSelectedSlot] = useState<TimeSlot | null>(null)

  const days = getDays(7)

  useEffect(() => {
    setTimeSlots(generateTimeSlots(selectedDay))
    setSelectedSlot(null)
  }, [selectedDay])

  function goNext() {
    setDirection(1)
    setStep((s) => s + 1)
  }

  function goBack() {
    setDirection(-1)
    setStep((s) => s - 1)
  }

  function handleConfirm() {
    if (!selectedService || !selectedSlot) return
    const dateStr = selectedDay.toISOString().split('T')[0]
    router.push(
      `/paiement?service=${selectedService.id}&date=${dateStr}&slot=${encodeURIComponent(selectedSlot.start + ' - ' + selectedSlot.end)}`
    )
  }

  const canNext =
    (step === 0 && selectedService !== null) ||
    (step === 1 && selectedSlot !== null)

  return (
    <div className="max-w-2xl mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-6 text-center">Réserver un espace</h1>

      <ProgressBar step={step} />

      <div className="overflow-hidden">
        <AnimatePresence mode="wait" custom={direction}>
          {step === 0 && (
            <motion.div
              key="step-0"
              custom={direction}
              variants={slideVariants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            >
              <h2 className="text-lg font-semibold text-gray-800 mb-4">Choisissez votre espace</h2>
              <div className="flex flex-col gap-3">
                {services.map((service) => {
                  const selected = selectedService?.id === service.id
                  return (
                    <motion.button
                      key={service.id}
                      onClick={() => setSelectedService(service)}
                      whileTap={{ scale: 0.985 }}
                      className={`w-full text-left rounded-2xl border-2 p-4 transition-colors ${
                        selected
                          ? 'border-brand-600 bg-brand-50'
                          : 'border-gray-200 bg-white hover:border-brand-200'
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <div
                          className={`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${
                            selected ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-500'
                          }`}
                        >
                          {serviceIcons[service.icon]}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between mb-0.5">
                            <span className="font-semibold text-gray-900">{service.name}</span>
                            <span className="flex items-center gap-1.5 text-xs">
                              <span
                                className={`w-2 h-2 rounded-full ${
                                  service.available > 0 ? 'bg-emerald-400' : 'bg-red-400'
                                }`}
                              />
                              <span className={service.available > 0 ? 'text-emerald-600' : 'text-red-500'}>
                                {service.available} disponible(s)
                              </span>
                            </span>
                          </div>
                          <p className="text-sm text-gray-500 mb-2">{service.description}</p>
                          <div className="flex items-center gap-3 text-sm">
                            <span className="font-semibold text-brand-600">
                              {formatPrice(service.pricePerHour)}/h
                            </span>
                            <span className="text-gray-400">·</span>
                            <span className="text-gray-500">Caution {formatPrice(service.deposit)}</span>
                          </div>
                        </div>
                        {selected && (
                          <div className="w-5 h-5 rounded-full bg-brand-600 flex items-center justify-center flex-shrink-0 mt-0.5">
                            <Check className="w-3 h-3 text-white" />
                          </div>
                        )}
                      </div>
                    </motion.button>
                  )
                })}
              </div>
            </motion.div>
          )}

          {step === 1 && (
            <motion.div
              key="step-1"
              custom={direction}
              variants={slideVariants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            >
              <h2 className="text-lg font-semibold text-gray-800 mb-4">Choisissez votre créneau</h2>

              {/* Day picker */}
              <div className="flex gap-2 overflow-x-auto pb-2 mb-5 scrollbar-hide -mx-4 px-4">
                {days.map((day, i) => {
                  const selected = day.toDateString() === selectedDay.toDateString()
                  return (
                    <motion.button
                      key={i}
                      onClick={() => setSelectedDay(day)}
                      whileTap={{ scale: 0.93 }}
                      className={`flex-shrink-0 w-14 py-2.5 rounded-xl flex flex-col items-center gap-0.5 border-2 transition-colors ${
                        selected
                          ? 'border-brand-600 bg-brand-600 text-white'
                          : 'border-gray-200 bg-white text-gray-700 hover:border-brand-300'
                      }`}
                    >
                      <span className="text-xs font-medium opacity-80">{DAY_NAMES[day.getDay()]}</span>
                      <span className="text-base font-bold">{day.getDate()}</span>
                      <span className="text-xs opacity-70">{MONTH_NAMES[day.getMonth()]}</span>
                    </motion.button>
                  )
                })}
              </div>

              {/* Time slots grid */}
              <div className="bg-white rounded-2xl border border-gray-100 p-4">
                <p className="text-sm text-gray-500 mb-3">
                  Créneaux disponibles — {formatShortDate(selectedDay)}
                </p>
                <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
                  {timeSlots.map((slot) => {
                    const isSelected = selectedSlot?.id === slot.id
                    return (
                      <motion.button
                        key={slot.id}
                        onClick={() => slot.available && setSelectedSlot(slot)}
                        whileTap={slot.available ? { scale: 0.93 } : {}}
                        disabled={!slot.available}
                        className={`rounded-xl py-2 px-1 text-sm font-medium transition-colors ${
                          !slot.available
                            ? 'bg-gray-50 text-gray-300 line-through cursor-not-allowed'
                            : isSelected
                            ? 'bg-brand-600 text-white shadow-sm'
                            : 'bg-brand-50 text-brand-700 hover:bg-brand-100'
                        }`}
                      >
                        {slot.start}
                      </motion.button>
                    )
                  })}
                </div>
              </div>

              {selectedSlot && (
                <motion.div
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="mt-3 bg-brand-50 rounded-xl px-4 py-3 text-sm text-brand-700 font-medium"
                >
                  Créneau sélectionné : {selectedSlot.start} – {selectedSlot.end}
                </motion.div>
              )}
            </motion.div>
          )}

          {step === 2 && (
            <motion.div
              key="step-2"
              custom={direction}
              variants={slideVariants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            >
              <h2 className="text-lg font-semibold text-gray-800 mb-4">Récapitulatif</h2>

              {selectedService && selectedSlot && (
                <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                  {/* Header */}
                  <div className="bg-gradient-to-r from-brand-600 to-brand-700 p-5 text-white">
                    <div className="flex items-center gap-3">
                      <div className="bg-white/20 rounded-xl p-2.5">
                        {serviceIcons[selectedService.icon]}
                      </div>
                      <div>
                        <p className="font-bold text-lg">{selectedService.name}</p>
                        <p className="text-brand-100 text-sm">{selectedService.description}</p>
                      </div>
                    </div>
                  </div>

                  {/* Details */}
                  <div className="p-5 flex flex-col gap-3">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-500">Date</span>
                      <span className="font-medium text-gray-900">
                        {selectedDay.toLocaleDateString('fr-FR', {
                          weekday: 'long',
                          day: 'numeric',
                          month: 'long',
                        })}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-500">Horaire</span>
                      <span className="font-medium text-gray-900">
                        {selectedSlot.start} – {selectedSlot.end}
                      </span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-500">Tarif</span>
                      <span className="font-medium text-gray-900">
                        {formatPrice(selectedService.pricePerHour)}/h
                      </span>
                    </div>
                    <div className="border-t border-gray-100 pt-3 flex justify-between">
                      <span className="text-gray-700 font-medium">Caution à payer</span>
                      <span className="font-bold text-brand-600 text-lg">
                        {formatPrice(selectedService.deposit)}
                      </span>
                    </div>
                    <p className="text-xs text-gray-400">
                      Vous serez remboursé de la différence entre la caution et le coût réel de votre utilisation.
                    </p>
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Navigation buttons */}
      <div className="flex items-center justify-between mt-8 gap-3">
        {step > 0 ? (
          <motion.button
            onClick={goBack}
            whileTap={{ scale: 0.97 }}
            className="flex items-center gap-1.5 px-5 py-3 rounded-xl border-2 border-gray-200 text-gray-700 font-medium text-sm hover:border-gray-300 transition-colors"
          >
            <ChevronLeft className="w-4 h-4" />
            Retour
          </motion.button>
        ) : (
          <div />
        )}

        {step < 2 ? (
          <motion.button
            onClick={goNext}
            disabled={!canNext}
            whileTap={canNext ? { scale: 0.97 } : {}}
            className={`flex items-center gap-1.5 px-6 py-3 rounded-xl font-semibold text-sm transition-colors ${
              canNext
                ? 'bg-brand-600 text-white hover:bg-brand-700'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed'
            }`}
          >
            Suivant
            <ChevronRight className="w-4 h-4" />
          </motion.button>
        ) : (
          <motion.button
            onClick={handleConfirm}
            whileTap={{ scale: 0.97 }}
            whileHover={{ scale: 1.02 }}
            className="flex items-center gap-2 px-6 py-3 rounded-xl bg-brand-600 text-white font-semibold text-sm hover:bg-brand-700 transition-colors"
          >
            Confirmer et payer
            <ChevronRight className="w-4 h-4" />
          </motion.button>
        )}
      </div>
    </div>
  )
}

export default function ReserverPage() {
  return (
    <PageTransition>
      <Suspense fallback={<div className="flex items-center justify-center min-h-[60vh] text-gray-400">Chargement...</div>}>
        <BookingContent />
      </Suspense>
    </PageTransition>
  )
}
