import { StepState, StepType, UploadFlow } from "./UploadFlow"
import { useRsi } from "../hooks/useRsi"
import { useRef, useState, useEffect } from "react"
import { steps, stepTypeToStepIndex, stepIndexToStepType } from "../utils/steps"
import { CgCheck } from "react-icons/cg"

const CheckIcon = ({ color }: { color: string }) => <CgCheck size="24" className={color} />

export const Steps = () => {
  const { initialStepState, translations, isNavigationEnabled, isOpen } = useRsi()
  const initialStep = stepTypeToStepIndex(initialStepState?.type)
  const [activeStep, setActiveStep] = useState(initialStep)
  const [state, setState] = useState<StepState>(initialStepState || { type: StepType.upload })
  const history = useRef<StepState[]>([])
  const prevIsOpen = useRef(isOpen)

  // Reset state when dialog is reopened
  useEffect(() => {
    // Check if dialog was closed and is now open again
    if (isOpen && !prevIsOpen.current) {
      // Reset to initial state
      setActiveStep(initialStep)
      setState(initialStepState || { type: StepType.upload })
      history.current = []
    }
    
    // Update previous isOpen value
    prevIsOpen.current = isOpen
  }, [isOpen, initialStep, initialStepState])

  const onClickStep = (stepIndex: number) => {
    const type = stepIndexToStepType(stepIndex)
    const historyIdx = history.current.findIndex((v) => v.type === type)
    if (historyIdx === -1) return
    const nextHistory = history.current.slice(0, historyIdx + 1)
    history.current = nextHistory
    setState(nextHistory[nextHistory.length - 1])
    setActiveStep(stepIndex)
  }

  const onBack = () => {
    onClickStep(Math.max(activeStep - 1, 0))
  }

  const onNext = (v: StepState) => {
    history.current.push(state)
    setState(v)
    
    if (v.type === StepType.validateData && 'isFromScratch' in v && v.isFromScratch) {
      // If starting from scratch, jump directly to the validation step
      const validationStepIndex = steps.indexOf('validationStep')
      setActiveStep(validationStepIndex)
    } else if (v.type !== StepType.selectSheet) {
      setActiveStep(activeStep + 1)
    }
  }

  return (
    <>
      <div className="hidden border-b bg-muted px-4 py-6 md:block">
        <nav className="mx-auto flex items-center justify-center gap-4 lg:gap-24" aria-label="Steps">
          {steps.map((key, index) => {
            const isActive = index === activeStep
            const isCompleted = index < activeStep
            return (
              <div key={key} className="flex items-center">
                <button
                  className={`group flex items-center ${isNavigationEnabled ? 'cursor-pointer' : 'cursor-default'}`}
                  onClick={isNavigationEnabled ? () => onClickStep(index) : undefined}
                  disabled={!isNavigationEnabled}
                >
                  <div className={`flex shrink-0 h-10 w-10 items-center justify-center rounded-full border-2 ${
                    isActive 
                      ? 'border-primary bg-primary text-primary-foreground'
                      : isCompleted
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-muted-foreground/20 bg-background'
                  }`}>
                    {isCompleted ? (
                      <CheckIcon color="text-primary-foreground" />
                    ) : (
                      <span className={`text-sm font-medium ${
                        isActive ? 'text-primary-foreground' : 'text-muted-foreground'
                      }`}>
                        {index + 1}
                      </span>
                    )}
                  </div>
                  <span className={`ml-2 text-sm font-medium ${
                    isActive ? 'text-foreground' : 'text-muted-foreground'
                  }`}>
                    {translations[key].title}
                  </span>
                </button>
              </div>
            )
          })}
        </nav>
      </div>
      <UploadFlow state={state} onNext={onNext} onBack={isNavigationEnabled ? onBack : undefined} />
    </>
  )
}
