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

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

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

  // Clear previous session on mount so each open starts fresh.
  // Steps unmounts when the dialog closes (Radix portal), so every open = fresh mount.
  useEffect(() => {
    clearSession()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const onClickStep = (stepIndex: number) => {
    const type = stepIndexToStepType(stepIndex)
    let historyIdx = history.current.findIndex((v) => v.type === type)

    // Special case: step index 0 could be either upload or selectSheet
    // If we didn't find upload, also check for selectSheet
    if (historyIdx === -1 && stepIndex === 0) {
      historyIdx = history.current.findIndex((v) => v.type === StepType.selectSheet)
    }

    if (historyIdx === -1) return
    const nextHistory = history.current.slice(0, historyIdx + 1)
    history.current = nextHistory
    setState(nextHistory[nextHistory.length - 1])
    setActiveStep(stepIndex)
  }

  const onBack = () => {
    // For back navigation, we want to go to the previous entry in history
    // rather than relying on step index, since selectSheet shares index with upload
    if (history.current.length > 0) {
      const previousState = history.current[history.current.length - 1]
      history.current = history.current.slice(0, -1)
      setState(previousState)
      setActiveStep(stepTypeToStepIndex(previousState.type))
    }
  }

  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) {
      // Use the step type to determine the correct index directly,
      // rather than incrementing, to avoid stale closure issues
      const targetIndex = stepTypeToStepIndex(v.type)
      setActiveStep(targetIndex)
    }
  }

  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} />
    </>
  )
}
