"use client"

import { useState } from "react"
import { FastForward } from "lucide-react"
import { Button } from "@/components/ui/button"
import ProgressSteps from "@/components/onboarding/progress-steps"
import StepNavigation from "@/components/onboarding/step-navigation"
import LogoBox from "@/components/dashboard/logo-box"
import { ApiKeyState, StepConfig, StepsState } from "@/app/(auth)/onboarding/types"
import { RenderStepContent } from "./step-content-renderer"

interface OnboardingFlowProps {
  steps: StepConfig[]
  title: string
  description?: string
  showSkip?: boolean
  onComplete: () => Promise<void>
  onSkip?: () => Promise<void>
  initialStepsState?: StepsState
  hasExistingApiKey: boolean
  showNewKeyMessage: boolean
}

export default function OnboardingFlow({
  steps,
  title,
  description,
  showSkip = false,
  onComplete,
  onSkip,
  hasExistingApiKey = false,
  showNewKeyMessage = false,
  initialStepsState = { current: { cli: 1 }, completed: { cli: [] } },
}: OnboardingFlowProps) {
  // State for steps
  const [stepsState, setStepsState] = useState<StepsState>(initialStepsState)
  const [activeInitStep, setActiveInitStep] = useState(1)
  const [apiKeyState, setApiKeyState] = useState<ApiKeyState>({
    name: "Secret Key",
    key: "",
    error: "",
  })
  const [generatingKey, setGeneratingKey] = useState(false)

  // Current step and steps array
  const getCurrentStep = (): number => stepsState.current.cli
  const getCompletedSteps = (): number[] => stepsState.completed.cli
  const getSteps = () => steps

  // Move to next step

  const nextStep = async () => {
    const currentStep = getCurrentStep()
    const stepsArr = getSteps()
    const isLastStep = currentStep === stepsArr.length
    const wasAlreadyCompleted = getCompletedSteps().includes(currentStep)

    // Mark current step as completed if not already
    if (!wasAlreadyCompleted) {
      setStepsState(prev => ({
        ...prev,
        completed: {
          ...prev.completed,
          cli: [...prev.completed.cli, currentStep],
        },
      }))
    }
    // Move to next step if not on last step
    if (!isLastStep) {
      setStepsState(prev => ({
        ...prev,
        current: {
          ...prev.current,
          cli: prev.current.cli + 1,
        },
      }))
    }
    // If this is the last step
    else if (isLastStep) {
      // Call onComplete for last step completion
      await onComplete()
    }
  }
  // Go back to previous step
  const prevStep = () => {
    setStepsState(prev => ({
      ...prev,
      current: {
        ...prev.current,
        cli: Math.max(prev.current.cli - 1, 1),
      },
    }))
  }

  // Navigate to a specific step (only if it's completed or the current step)
  const goToStep = (stepId: number) => {
    const currentCompleted = getCompletedSteps()
    if (currentCompleted.includes(stepId) || stepId === getCurrentStep()) {
      setStepsState(prev => ({
        ...prev,
        current: {
          ...prev.current,
          cli: stepId,
        },
      }))

      // Reset active init step when navigating
      if (stepId === 2) {
        setActiveInitStep(1)
      }
    }
  }

  return (
    <div className="flex flex-col items-center min-h-screen px-6 py-12">
      <div className="w-full max-w-4xl">
        <div className="flex flex-col items-center mb-8">
          <LogoBox />
          <h1 className="text-3xl font-bold mt-4 text-foreground text-center">{title}</h1>
          {description && <p className="text-muted-foreground mt-2 text-center">{description}</p>}
        </div>

        {/* Integration Steps */}
        <div className="mb-10 w-full">
          {/* Progress steps */}
          <ProgressSteps
            steps={getSteps()}
            currentStep={getCurrentStep()}
            completedSteps={getCompletedSteps()}
            goToStep={goToStep}
          />

          {/* Current step content */}
          <div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col items-center">
            <div className="text-center w-full mb-6">
              <h3 className="text-xl font-medium mb-2 text-foreground">
                {getCurrentStep() === getSteps().length
                  ? null
                  : getSteps().find(s => s.id === getCurrentStep())?.title}
              </h3>
              <p className="text-muted-foreground">
                {getSteps().find(s => s.id === getCurrentStep())?.description}
              </p>
            </div>

            {/* Dynamic step content */}
            <div className="w-full flex justify-center">
              <div className="w-full max-w-2xl">
                {RenderStepContent({
                  stepConfig: getSteps().find(s => s.id === getCurrentStep())!,
                  apiKeyState,
                  setApiKeyState,
                  generatingKey,
                  setGeneratingKey,
                  activeInitStep,
                  setActiveInitStep,
                  hasExistingApiKey,
                  showNewKeyMessage,
                })}
              </div>
            </div>

            {/* Navigation buttons */}
            <div className="w-full max-w-2xl mt-6">
              <StepNavigation
                currentStep={getCurrentStep()}
                totalSteps={getSteps().length}
                completedSteps={getCompletedSteps()}
                onBack={prevStep}
                onNext={nextStep}
              />
            </div>
          </div>
        </div>
        <div className="mt-4 mb-6 text-center sm:text-sm text-xs text-muted-foreground px-4 sm:px-0">
          <span className="flex items-center justify-center gap-1.5">
            Need help? For more details check out our
            <a
              href="https://docs.codeflash.ai/getting-started/local-installation"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline font-medium mx-1 flex items-center"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="size-4 text-primary mr-1"
              >
                <path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"></path>
              </svg>
              documentation
            </a>
          </span>
        </div>

        {/* Skip button */}
        {showSkip && onSkip && (
          <div className="mt-6 flex justify-center">
            <Button
              variant="ghost"
              className="text-muted-foreground hover:text-foreground text-sm"
              onClick={onSkip}
            >
              <FastForward className="w-4 h-4 mr-2" />
              Skip setup
            </Button>
          </div>
        )}
      </div>
    </div>
  )
}
