'use client'

import React, {
  useState,
  createContext,
  useContext,
  useEffect,
  useCallback,
} from 'react'
import Navigation from './Navigation'
import { cn } from '@/lib/utils/tw-merge'
import { useScreenSize } from '@/lib/hooks/useScreenSize'
import Content from './Content'
import Indicators from './Indicator'

// Types
export type Step = {
  id: string | number
  label: string
  icon?: React.ReactNode
}

interface StepperProps {
  step?: number
  totalSteps: number
  className?: string
  children?: React.ReactNode
  onStepChange?: (step: number) => void
}

// Context to share state between compound components
type StepperContextType = {
  currentStep: number
  totalSteps: number
  isFirstStep: boolean
  isLastStep: boolean
  progressPercentage: number
  isMobile: boolean
  setCurrentStep: (step: number) => void
  goToNext: () => void
  goToPrevious: () => void
}

const StepperContext = createContext<StepperContextType | undefined>(undefined)

// Hook to use the stepper context
export const useStepperContext = () => {
  const context = useContext(StepperContext)

  if (!context) {
    throw new Error(
      'Stepper compound components must be used within a Stepper component',
    )
  }

  return context
}

const Stepper = ({
  step = 0,
  totalSteps,
  onStepChange,
  className,
  children,
}: StepperProps) => {
  const [currentStep, setCurrentStep] = useState(step)
  const screenSize = useScreenSize()

  const handleStepChange = useCallback(
    (step: number) => {
      setCurrentStep(step)
      if (onStepChange) {
        onStepChange(step)
      }
    },
    [onStepChange],
  )

  const goToNext = () => {
    if (currentStep < totalSteps - 1) {
      handleStepChange(currentStep + 1)
    }
  }

  const goToPrevious = () => {
    if (currentStep > 0) {
      handleStepChange(currentStep - 1)
    }
  }

  const isFirstStep = currentStep === 0
  const isLastStep = currentStep === totalSteps - 1
  const progressPercentage = (currentStep / (totalSteps - 1)) * 100

  const contextValue = {
    currentStep,
    totalSteps,
    isFirstStep,
    isLastStep,
    progressPercentage,
    isMobile: screenSize < 576,
    setCurrentStep: handleStepChange,
    goToNext,
    goToPrevious,
  }

  useEffect(() => {
    handleStepChange(step)
  }, [step, handleStepChange])

  return (
    <StepperContext.Provider value={contextValue}>
      <div className={cn('w-full space-y-6', className)}>{children}</div>
    </StepperContext.Provider>
  )
}

// Assign sub-components to the main component
Stepper.Content = Content
Stepper.Indicators = Indicators
Stepper.Navigation = Navigation

export default Stepper
