'use client'

import React, {
  useState,
  createContext,
  useContext,
  useEffect,
  ButtonHTMLAttributes,
  forwardRef,
} from 'react'
import { Button } from '@/components/shadcn/ui/button'
import { Check, ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '../lib/utils/tw-merge'
import { useWindowSize } from '@/lib/hooks/useWindowSize'

// 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
  setCurrentStep: (step: number) => void
  goToNext: () => void
  goToPrevious: () => void
  isMobile: boolean
}

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

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

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

  return context
}

// Main Stepper component
const Stepper = ({
  step = 0,
  totalSteps,
  onStepChange,
  className,
  children,
}: StepperProps) => {
  const [currentStep, setCurrentStep] = useState(step)
  const { width: windowWidth } = useWindowSize()

  const handleStepChange = (step: number) => {
    setCurrentStep(step)
    if (onStepChange) {
      onStepChange(step)
    }
  }

  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: windowWidth < 576,
    setCurrentStep: handleStepChange,
    goToNext,
    goToPrevious,
  }

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

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

// Indicator component
interface IndicatorsProps {
  className?: string
  labels?: string[]
  icons?: React.ReactNode[]
}

const Indicators = ({
  className,
  labels = [],
  icons = [],
}: IndicatorsProps) => {
  const { currentStep, totalSteps, isMobile } = useStepperContext()

  return (
    <div
      className={cn(
        'relative',
        'flex flex-row items-center justify-between',
        className,
      )}
    >
      {/* Track line - horizontal or vertical based on screen size */}
      <div className="absolute left-0 w-full top-1/3 h-1 bg-gray-200 rounded-full z-1" />

      {/* Progress Line - horizontal or vertical based on screen size */}
      <div
        className="absolute left-0 h-1 top-1/3 rounded-full bg-blue-800 transition-all duration-300 ease-in-out z-1"
        style={{ width: `${(currentStep / (totalSteps - 1)) * 100}%` }}
      />

      {Array.from({ length: totalSteps }).map((_, index) => {
        const status =
          index < currentStep
            ? 'completed'
            : index === currentStep
              ? 'current'
              : 'upcoming'

        return (
          <div
            key={index}
            className={cn(`relative z-1`, 'flex flex-col items-center')}
          >
            {/* Step icon/number */}
            <div
              className={cn(
                'flex items-center justify-center rounded-full border-2 text-sm font-medium cursor-pointer transition-colors duration-200',
                isMobile ? 'h-10 w-10' : 'h-10 w-10',
                status === 'current' &&
                  'bg-blue-800 border-blue-800 text-white',
                status === 'completed' &&
                  'border-blue-800 bg-blue-800 text-white',
                status === 'upcoming' &&
                  'border-gray-300 bg-gray-100 text-gray-500',
              )}
            >
              {status === 'completed' ? (
                <Check className="h-5 w-5" />
              ) : (
                <>{icons[index] || index + 1}</>
              )}
            </div>

            {/* Label if provided */}
            {labels[index] && (
              <div className={cn('mt-2 text-center')}>
                <div
                  className={cn(
                    'font-medium',
                    isMobile ? 'text-xs' : 'text-sm',
                    status === 'current'
                      ? 'font-medium text-blue-800'
                      : 'text-slate-500',
                  )}
                >
                  {labels[index]}
                </div>
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}

// Content sub-component
interface ContentProps {
  className?: string
  children: React.ReactNode | React.ReactNode[]
}

const Content = forwardRef<HTMLDivElement, ContentProps>(function Content(
  { className, children },
  ref,
) {
  const { currentStep, isMobile } = useStepperContext()

  // Handle array of children
  if (Array.isArray(children)) {
    return (
      <div className={cn(isMobile ? 'mt-4' : 'mt-6', className)} ref={ref}>
        {React.Children.toArray(children)[currentStep] || null}
      </div>
    )
  }

  // If not an array, just render the children
  return (
    <div className={cn(isMobile ? 'mt-4' : 'mt-6', className)} ref={ref}>
      {children}
    </div>
  )
})

// Navigation sub-component
interface NavigationProps {
  className?: string
  showStepCount?: boolean
  prevLabel?: string
  nextLabel?: string
  variant?: 'default' | 'outline' | 'ghost'
  disabled?: boolean
  prevIcon?: React.ReactNode
  nextIcon?: React.ReactNode
  prevButtonType?: ButtonHTMLAttributes<HTMLButtonElement>['type']
  nextButtonType?: ButtonHTMLAttributes<HTMLButtonElement>['type']
  prevButtonHandler?: () => void
  nextButtonHandler?: () => void
}

const Navigation = ({
  className,
  showStepCount = true,
  prevLabel = 'Previous',
  nextLabel = 'Next',
  variant = 'default',
  prevButtonType = 'button',
  nextButtonType = 'button',
  disabled = false,
  prevButtonHandler,
  nextButtonHandler,
  prevIcon = <ChevronLeft className="mr-1 h-4 w-4" />,
  nextIcon = <ChevronRight className="ml-1 h-4 w-4" />,
}: NavigationProps) => {
  const {
    currentStep,
    totalSteps,
    isFirstStep,
    isLastStep,
    goToPrevious,
    goToNext,
  } = useStepperContext()

  return (
    <div
      className={cn(
        'flex items-center flex-col sm:flex-row justify-between mt-6',
        className,
      )}
    >
      {showStepCount ? (
        <div className="text-sm text-gray-500">
          Step {currentStep + 1} of {totalSteps}
        </div>
      ) : (
        <div />
      )}

      <div className="flex space-x-2 mt-4 sm:mt-0">
        <Button
          type={prevButtonType}
          variant={variant === 'default' ? 'outline' : variant}
          size="sm"
          onClick={() => {
            if (prevButtonHandler) {
              prevButtonHandler()
            } else {
              goToPrevious()
            }
          }}
          disabled={isFirstStep}
        >
          {prevIcon}
          {prevLabel}
        </Button>
        <Button
          type={nextButtonType}
          variant={variant}
          size="sm"
          onClick={() => {
            if (nextButtonHandler) {
              nextButtonHandler()
            } else {
              goToNext()
            }
          }}
          disabled={isLastStep || disabled}
        >
          {nextLabel}
          {nextIcon}
        </Button>
      </div>
    </div>
  )
}

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

export default Stepper
