'use client'

import { useState } from 'react'
import { AnimatePresence, motion } from 'framer-motion'
import { BookingProgressBar } from './BookingProgressBar'
import { BookingStep1Form } from './BookingStep1'
import { BookingStep2Form } from './BookingStep2'
import { BookingStep3Form } from './BookingStep3'
import { BookingSuccessState } from './BookingSuccessState'
import type { BookingStep1, BookingStep2, BookingStep3 } from '@/lib/validations/bookingSchema'

type AllData = Partial<BookingStep1 & BookingStep2 & BookingStep3>

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

export function BookingForm() {
  const [step, setStep] = useState(1)
  const [direction, setDirection] = useState(1)
  const [formData, setFormData] = useState<AllData>({})
  const [success, setSuccess] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const goNext = (data: Partial<AllData>) => {
    setDirection(1)
    setFormData((prev) => ({ ...prev, ...data }))
    setStep((s) => s + 1)
  }

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

  const handleFinalSubmit = async (step3Data: BookingStep3) => {
    const all = { ...formData, ...step3Data }
    setLoading(true)
    setError(null)

    try {
      const res = await fetch('/api/booking', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(all),
      })

      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.error || 'Failed to submit')
      }

      setSuccess(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  if (success) {
    return <BookingSuccessState />
  }

  return (
    <div>
      {!success && <BookingProgressBar currentStep={step} totalSteps={3} />}

      <AnimatePresence mode="wait" custom={direction}>
        <motion.div
          key={step}
          custom={direction}
          variants={slideVariants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] as [number, number, number, number] }}
        >
          {step === 1 && (
            <BookingStep1Form
              defaultValues={formData}
              onNext={(data) => goNext(data)}
            />
          )}
          {step === 2 && (
            <BookingStep2Form
              defaultValues={formData}
              onNext={(data) => goNext(data)}
              onBack={goBack}
            />
          )}
          {step === 3 && (
            <BookingStep3Form
              defaultValues={formData}
              onNext={handleFinalSubmit}
              onBack={goBack}
              isLoading={loading}
            />
          )}
        </motion.div>
      </AnimatePresence>

      {error && (
        <p className="text-sm mt-4 text-center" style={{ color: '#fca5a5' }}>
          {error}
        </p>
      )}
    </div>
  )
}
