"use client"

import React from "react"
import { motion } from "framer-motion"
import { CheckCircle, Circle, XCircle } from "lucide-react"
import { cn } from "../../lib/utils"
import { useFormWizard } from "./form-wizard-context"
import { FormWizardProps } from "./types"

interface FormWizardProgressProps {
  className?: string
  progressType?: FormWizardProps['progressType']
  orientation?: FormWizardProps['orientation']
  showStepNumbers?: boolean
  showStepTitles?: boolean
  stepIconPosition?: FormWizardProps['stepIconPosition']
  completedStepIcon?: React.ReactNode
  activeStepIcon?: React.ReactNode
  errorStepIcon?: React.ReactNode
}

export const FormWizardProgress: React.FC<FormWizardProgressProps> = ({
  className,
  progressType = 'linear',
  orientation = 'horizontal',
  showStepNumbers = true,
  showStepTitles = true,
  stepIconPosition = 'top',
  completedStepIcon = <CheckCircle className="w-5 h-5" />,
  activeStepIcon,
  errorStepIcon = <XCircle className="w-5 h-5" />
}) => {
  const { steps, currentStep, isStepCompleted, isStepAccessible, error } = useFormWizard()

  if (progressType === 'linear') {
    return (
      <div className={cn(
        "relative w-full",
        orientation === 'vertical' ? "flex flex-col space-y-8" : "",
        className
      )}>
        {orientation === 'horizontal' ? (
          <div className="relative w-full">
            {/* Steps Container with connecting lines */}
            <div className="relative flex items-start justify-between w-full">
              {steps.map((step, index) => {
                const isActive = index === currentStep
                const isCompleted = isStepCompleted(index)
                const isAccessible = isStepAccessible(index)
                const hasError = isActive && error
                
                const StepIcon = typeof step.icon === 'function' 
                  ? step.icon({ isActive, isCompleted })
                  : step.icon

                return (
                  <div key={step.id} className="relative flex-1 flex flex-col items-center">
                    {/* Step Title & Description - Above the circle */}
                    {showStepTitles && (
                      <div className="text-center mb-3 min-h-[40px] px-2">
                        <p className={cn(
                          "text-sm font-semibold transition-colors",
                          isActive && "text-primary",
                          isCompleted && !isActive && "text-primary",
                          !isActive && !isCompleted && "text-muted-foreground"
                        )}>
                          {step.title}
                        </p>
                        {step.description && (
                          <p className="text-xs text-muted-foreground mt-1">
                            {step.description}
                          </p>
                        )}
                      </div>
                    )}

                    {/* Step Circle Container with line */}
                    <div className="relative flex items-center w-full">
                      {/* Connecting Line - Positioned after each circle except the last */}
                      {index < steps.length - 1 && (
                        <div 
                          className="absolute left-1/2 w-full h-[2px]"
                          style={{ 
                            width: 'calc(100% + 24px)',
                            marginLeft: '24px'
                          }}
                        >
                          <div className="h-full bg-border" />
                          {index < currentStep && (
                            <motion.div
                              className="absolute inset-0 bg-primary"
                              initial={{ scaleX: 0 }}
                              animate={{ scaleX: 1 }}
                              transition={{ duration: 0.5, delay: index * 0.1 }}
                              style={{ transformOrigin: 'left' }}
                            />
                          )}
                        </div>
                      )}

                      {/* Step Circle */}
                      <motion.div
                        initial={{ scale: 0.8 }}
                        animate={{ scale: isActive ? 1.05 : 1 }}
                        transition={{ duration: 0.2 }}
                        className={cn(
                          "relative z-10 flex items-center justify-center rounded-full transition-all duration-300 mx-auto",
                          "w-12 h-12 border-2",
                          isActive && "border-primary bg-primary text-primary-foreground shadow-lg shadow-primary/20",
                          isCompleted && !isActive && "border-primary bg-primary text-primary-foreground",
                          !isActive && !isCompleted && isAccessible && "border-border bg-background text-muted-foreground hover:border-accent",
                          !isAccessible && "border-border/50 bg-muted text-muted-foreground/50 cursor-not-allowed",
                          hasError && "border-destructive bg-destructive text-destructive-foreground"
                        )}
                      >
                        {hasError ? (
                          errorStepIcon
                        ) : isCompleted && !isActive ? (
                          completedStepIcon
                        ) : isActive && activeStepIcon ? (
                          activeStepIcon
                        ) : StepIcon ? (
                          <span className="w-5 h-5 flex items-center justify-center">{StepIcon}</span>
                        ) : showStepNumbers ? (
                          <span className="text-sm font-semibold">{index + 1}</span>
                        ) : (
                          <Circle className="w-4 h-4" />
                        )}
                      </motion.div>
                    </div>

                    {/* Step Label Below Circle */}
                    <div className="mt-3">
                      <p className="text-xs text-muted-foreground font-medium">
                        Step {index + 1} of {steps.length}
                      </p>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        ) : (
          // Vertical orientation
          <div className="relative pl-12">
            {/* Vertical Progress Line */}
            {steps.length > 1 && (
              <>
                <div className="absolute left-6 top-8 bottom-8 w-[2px] bg-border" />
                <motion.div
                  className="absolute left-6 top-8 w-[2px] bg-primary"
                  initial={{ height: 0 }}
                  animate={{ 
                    height: `${(currentStep / (steps.length - 1)) * (100 - 16)}%`
                  }}
                  transition={{ duration: 0.5 }}
                />
              </>
            )}

            {steps.map((step, index) => {
              const isActive = index === currentStep
              const isCompleted = isStepCompleted(index)
              const isAccessible = isStepAccessible(index)
              const hasError = isActive && error
              
              const StepIcon = typeof step.icon === 'function' 
                ? step.icon({ isActive, isCompleted })
                : step.icon

              return (
                <div key={step.id} className="relative flex items-center mb-8 last:mb-0">
                  {/* Step Circle */}
                  <motion.div
                    initial={{ scale: 0.8 }}
                    animate={{ scale: isActive ? 1.05 : 1 }}
                    className={cn(
                      "absolute left-0 z-20 flex items-center justify-center rounded-full border-2 transition-all duration-300",
                      "w-12 h-12",
                      isActive && "border-primary bg-primary text-primary-foreground shadow-lg",
                      isCompleted && !isActive && "border-primary bg-primary text-primary-foreground",
                      !isActive && !isCompleted && isAccessible && "border-border bg-background text-muted-foreground hover:border-accent",
                      !isAccessible && "border-border/50 bg-muted text-muted-foreground/50 cursor-not-allowed",
                      hasError && "border-destructive bg-destructive text-destructive-foreground"
                    )}
                  >
                    {hasError ? (
                      errorStepIcon
                    ) : isCompleted && !isActive ? (
                      completedStepIcon
                    ) : isActive && activeStepIcon ? (
                      activeStepIcon
                    ) : StepIcon ? (
                      <span className="w-5 h-5 flex items-center justify-center">{StepIcon}</span>
                    ) : showStepNumbers ? (
                      <span className="text-sm font-semibold">{index + 1}</span>
                    ) : (
                      <Circle className="w-4 h-4" />
                    )}
                  </motion.div>

                  {/* Step Content */}
                  <div className="ml-16">
                    {showStepTitles && (
                      <>
                        <p className={cn(
                          "text-sm font-semibold transition-colors",
                          isActive && "text-primary",
                          isCompleted && !isActive && "text-primary",
                          !isActive && !isCompleted && "text-muted-foreground"
                        )}>
                          {step.title}
                        </p>
                        {step.description && (
                          <p className="text-xs text-muted-foreground mt-1">
                            {step.description}
                          </p>
                        )}
                      </>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>
    )
  }

  if (progressType === 'dots') {
    return (
      <div className={cn("flex items-center justify-center space-x-2", className)}>
        {steps.map((_, index) => {
          const isActive = index === currentStep
          const isCompleted = isStepCompleted(index)
          
          return (
            <motion.div
              key={index}
              initial={{ scale: 0.8 }}
              animate={{ scale: isActive ? 1.2 : 1 }}
              className={cn(
                "rounded-full transition-all duration-300",
                isActive ? "w-3 h-3 bg-primary" : "w-2 h-2",
                isCompleted && !isActive && "bg-primary/60",
                !isActive && !isCompleted && "bg-muted"
              )}
            />
          )
        })}
      </div>
    )
  }

  if (progressType === 'circular') {
    const progress = ((currentStep + 1) / steps.length) * 100
    const circumference = 2 * Math.PI * 45 // radius = 45
    const strokeDashoffset = circumference - (progress / 100) * circumference

    return (
      <div className={cn("relative w-36 h-36 mx-auto", className)}>
        <svg className="w-full h-full -rotate-90" viewBox="0 0 144 144">
          <circle
            cx="72"
            cy="72"
            r="45"
            fill="none"
            stroke="currentColor"
            strokeWidth="8"
            className="text-border"
          />
          <motion.circle
            cx="72"
            cy="72"
            r="45"
            fill="none"
            stroke="currentColor"
            strokeWidth="8"
            strokeDasharray={circumference}
            initial={{ strokeDashoffset: circumference }}
            animate={{ strokeDashoffset }}
            className="text-primary"
            transition={{ duration: 0.5 }}
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="text-center">
            <p className="text-3xl font-bold">{currentStep + 1}</p>
            <p className="text-sm text-muted-foreground">of {steps.length}</p>
          </div>
        </div>
      </div>
    )
  }

  return null
}