"use client"

import React from "react"
import { motion } from "framer-motion"
import { ChevronLeft, ChevronRight, Check, Loader2 } from "lucide-react"
import { Button } from "../ui/button"
import { cn } from "../../lib/utils"
import { useFormWizard } from "./form-wizard-context"

interface FormWizardNavigationProps {
  className?: string
  showStepIndicator?: boolean
  previousText?: string
  nextText?: string
  completeText?: string
  loadingText?: string
  onPreviousClick?: () => void
  onNextClick?: () => void
  onCompleteClick?: () => void
}

export const FormWizardNavigation: React.FC<FormWizardNavigationProps> = ({
  className,
  showStepIndicator = true,
  previousText = "Previous",
  nextText = "Next",
  completeText = "Complete",
  loadingText = "Processing...",
  onPreviousClick,
  onNextClick,
  onCompleteClick
}) => {
  const {
    steps,
    currentStep,
    isLoading,
    canGoNext,
    canGoPrevious,
    goToNext,
    goToPrevious,
    completeWizard
  } = useFormWizard()

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

  const handlePrevious = () => {
    onPreviousClick?.()
    goToPrevious()
  }

  const handleNext = () => {
    if (isLastStep) {
      onCompleteClick?.()
      completeWizard()
    } else {
      onNextClick?.()
      goToNext()
    }
  }

  return (
    <div className={cn("flex items-center justify-between", className)}>
      <div className="flex items-center gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={handlePrevious}
          disabled={!canGoPrevious || isLoading}
          className={cn(
            "transition-all duration-200",
            !canGoPrevious && "invisible"
          )}
        >
          <ChevronLeft className="w-4 h-4 mr-1" />
          {previousText}
        </Button>

        {showStepIndicator && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="px-3 py-1 text-sm text-muted-foreground"
          >
            Step {currentStep + 1} of {steps.length}
            {currentStepObj.isOptional && (
              <span className="ml-1 text-xs">(Optional)</span>
            )}
          </motion.div>
        )}
      </div>

      <Button
        type="button"
        onClick={handleNext}
        disabled={isLoading || (!canGoNext && !isLastStep)}
        className="min-w-[120px]"
      >
        {isLoading ? (
          <>
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            {loadingText}
          </>
        ) : isLastStep ? (
          <>
            <Check className="w-4 h-4 mr-2" />
            {completeText}
          </>
        ) : (
          <>
            {nextText}
            <ChevronRight className="w-4 h-4 ml-1" />
          </>
        )}
      </Button>
    </div>
  )
}