"use client"

import React from "react"
import { motion, AnimatePresence } from "framer-motion"
import { cn } from "../../lib/utils"
import { useFormWizard } from "./form-wizard-context"
import { FormWizardProps } from "./types"
import { Alert, AlertDescription } from "../ui/alert"
import { AlertCircle } from "lucide-react"

interface FormWizardStepProps {
  className?: string
  animationType?: FormWizardProps['animationType']
  animationDuration?: number
}

const animations = {
  slide: {
    initial: (direction: number) => ({
      x: direction > 0 ? 1000 : -1000,
      opacity: 0
    }),
    animate: {
      x: 0,
      opacity: 1
    },
    exit: (direction: number) => ({
      x: direction < 0 ? 1000 : -1000,
      opacity: 0
    })
  },
  fade: {
    initial: { opacity: 0 },
    animate: { opacity: 1 },
    exit: { opacity: 0 }
  },
  scale: {
    initial: { opacity: 0, scale: 0.8 },
    animate: { opacity: 1, scale: 1 },
    exit: { opacity: 0, scale: 0.8 }
  },
  none: {
    initial: {},
    animate: {},
    exit: {}
  }
}

export const FormWizardStep: React.FC<FormWizardStepProps> = ({
  className,
  animationType = 'slide',
  animationDuration = 0.3
}) => {
  const { steps, currentStep, goToNext, goToPrevious, goToStep, updateStepData, stepData, error } = useFormWizard()
  const [direction, setDirection] = React.useState(0)
  const previousStep = React.useRef(currentStep)

  React.useEffect(() => {
    setDirection(currentStep > previousStep.current ? 1 : -1)
    previousStep.current = currentStep
  }, [currentStep])

  const currentStepObj = steps[currentStep]
  const isFirstStep = currentStep === 0
  const isLastStep = currentStep === steps.length - 1

  const stepContentProps = {
    currentStep,
    totalSteps: steps.length,
    goToNext,
    goToPrevious,
    goToStep,
    isFirstStep,
    isLastStep,
    stepData: stepData[currentStepObj.id] || {},
    updateStepData: (data: any) => updateStepData(currentStepObj.id, data)
  }

  const content = typeof currentStepObj.content === 'function'
    ? currentStepObj.content(stepContentProps)
    : currentStepObj.content

  return (
    <AnimatePresence mode="wait" custom={direction}>
      <motion.div
        key={currentStep}
        custom={direction}
        variants={animations[animationType]}
        initial="initial"
        animate="animate"
        exit="exit"
        transition={{
          duration: animationDuration,
          ease: "easeInOut"
        }}
        className={cn("w-full", className)}
        data-wizard-step-content
      >
        <div className="space-y-4">
          {error && (
            <Alert variant="error">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
          {content}
        </div>
      </motion.div>
    </AnimatePresence>
  )
}