/* eslint-disable react-hooks/rules-of-hooks */
import {
  KeyRound,
  Copy,
  Check,
  Terminal,
  AlertCircle,
  ChevronLeft,
  ExternalLink,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useState } from "react"
import { ApiKeyState, StepConfig } from "@/app/(auth)/onboarding/types"
import { generateToken } from "@/app/(dashboard)/apikeys/tokenfuncs"

// Custom API Key Card Component
export const ApiKeyCard = ({
  label,
  value,
  onCopied,
}: {
  label: string
  value: string
  onCopied?: () => void
}) => {
  const [copied, setCopied] = useState(false)

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(value)
      setCopied(true)
      if (onCopied) onCopied()
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error("Failed to copy text: ", err)
    }
  }

  return (
    <div className="rounded-lg border border-border overflow-hidden bg-background shadow-sm">
      <div className="px-4 py-2 bg-muted flex justify-between items-center">
        <div className="flex items-center space-x-2">
          <Terminal size={14} className="text-foreground opacity-70" />
          <span className="text-xs font-medium">{label}</span>
        </div>
        <button
          onClick={copyToClipboard}
          className="text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 rounded p-1 transition-all"
          aria-label="Copy to clipboard"
        >
          {copied ? <Check size={16} className="text-green-500" /> : <Copy size={16} />}
        </button>
      </div>
      <div className="p-4 overflow-x-auto">
        <pre className="text-sm text-foreground font-mono whitespace-pre-wrap break-all">
          {value}
        </pre>
      </div>
    </div>
  )
}

// Step by step instruction component
export const StepInstruction = ({
  number,
  title,
  children,
  status = "default",
}: {
  number: number
  title: string
  children: React.ReactNode
  status?: "default" | "active" | "completed" | "warning"
}) => {
  const getStatusStyles = () => {
    switch (status) {
      case "active":
        return "border-primary bg-primary/5"
      case "completed":
        return "border-green-500 bg-green-50 dark:bg-green-950/20"
      case "warning":
        return "border-amber-500 bg-amber-50 dark:bg-amber-950/20"
      default:
        return "border-border bg-card"
    }
  }

  const getNumberStyles = () => {
    switch (status) {
      case "active":
        return "bg-primary text-white"
      case "completed":
        return "bg-green-500 text-white"
      case "warning":
        return "bg-amber-500 text-white"
      default:
        return "bg-muted text-muted-foreground"
    }
  }
  return (
    <div className={`p-4 rounded-lg border ${getStatusStyles()} transition-all`}>
      <div className="flex items-start gap-3">
        <div
          className={`rounded-full h-8 w-8 flex items-center justify-center text-xs font-medium ${getNumberStyles()} shrink-0 mt-0.5`}
        >
          {status === "completed" ? <Check size={14} /> : number}
        </div>
        <div className="space-y-2 w-full">
          <h2 className="text-xl font-medium text-slate-900 mb-4 dark:text-gray-200">{title}</h2>
          {children}
        </div>
      </div>
    </div>
  )
}

interface RenderStepContentProps {
  stepConfig: StepConfig
  apiKeyState: ApiKeyState
  setApiKeyState: React.Dispatch<React.SetStateAction<ApiKeyState>>
  generatingKey: boolean
  setGeneratingKey: React.Dispatch<React.SetStateAction<boolean>>
  activeInitStep: number
  setActiveInitStep: React.Dispatch<React.SetStateAction<number>>
  hasExistingApiKey?: boolean
  showNewKeyMessage?: boolean
}

export function RenderStepContent({
  stepConfig,
  apiKeyState,
  setApiKeyState,
  generatingKey,
  setGeneratingKey,
  activeInitStep,
  setActiveInitStep,
  hasExistingApiKey = false,
  showNewKeyMessage = true,
}: RenderStepContentProps) {
  if (!stepConfig) return null

  const [showKeyGeneration, setShowKeyGeneration] = useState(!hasExistingApiKey)

  const handleGenerateApiKey = async (): Promise<void> => {
    if (!apiKeyState.name.trim()) {
      setApiKeyState(prev => ({
        ...prev,
        error: "API Key Name is required",
      }))
      return
    }

    setGeneratingKey(true)
    setApiKeyState(prev => ({
      ...prev,
      error: "",
    }))

    try {
      const data = await generateToken(apiKeyState.name)
      if (data.success) {
        setApiKeyState(prev => ({
          ...prev,
          key: data.token!,
        }))

        setActiveInitStep(3)
      } else {
        setApiKeyState(prev => ({
          ...prev,
          error: data.err!,
        }))
      }
    } catch {
      setApiKeyState(prev => ({
        ...prev,
        error: "Failed to generate API key. Please try again.",
      }))
    } finally {
      setGeneratingKey(false)
    }
  }

  const skipTokenGeneration = () => {
    setShowKeyGeneration(false)
    setActiveInitStep(3)
  }

  const setApiKeyName = (name: string) => {
    setApiKeyState(prev => ({
      ...prev,
      name,
      error: "",
    }))
  }

  switch (stepConfig.contentType) {
    case "installPackage":
      return (
        <div className="w-full">
          <Tabs defaultValue="pip" className="w-full">
            <TabsList className="w-full justify-start mb-4">
              <TabsTrigger value="pip" className="font-medium">
                pip
              </TabsTrigger>
              <TabsTrigger value="poetry" className="font-medium">
                Poetry
              </TabsTrigger>
              <TabsTrigger value="uv" className="font-medium">
                uv
              </TabsTrigger>
            </TabsList>
            <TabsContent value="pip" className="mt-0">
              <ApiKeyCard label="Terminal" value="pip install codeflash" />
            </TabsContent>
            <TabsContent value="poetry" className="mt-0">
              <ApiKeyCard label="Terminal" value="poetry add codeflash --dev" />
              <p className="text-sm text-muted-foreground mt-2 font-medium">
                Installs Codeflash as a development dependency (recommended). To install it as a
                main dependency, remove the --dev flag.
              </p>
            </TabsContent>
            <TabsContent value="uv" className="mt-0">
              <ApiKeyCard label="Terminal" value="uv add --dev codeflash" />
              <p className="text-sm text-muted-foreground mt-2 font-medium">
                Installs Codeflash as a development dependency (recommended). To install it as a
                main dependency, remove the --dev flag.
              </p>
            </TabsContent>
          </Tabs>
        </div>
      )

    case "initializeWithKey":
      return (
        <div className="space-y-4 w-full">
          <div className="space-y-3">
            <StepInstruction
              number={1}
              title="Generate a Codeflash API Key"
              status={
                activeInitStep === 2 ? "active" : activeInitStep > 2 ? "completed" : "default"
              }
            >
              {!apiKeyState.key ? (
                <div className="space-y-4">
                  <p className="text-sm text-muted-foreground font-medium">
                    {hasExistingApiKey
                      ? "You'll need an API key to authenticate your Codeflash requests"
                      : "Create an API key to authenticate your Codeflash requests and add it to your environment variables"}
                  </p>

                  {hasExistingApiKey && (
                    <div
                      className={`transition-all duration-300 ease-in-out ${showKeyGeneration ? "opacity-0 h-0 overflow-hidden" : "opacity-100"}`}
                    >
                      <div className="flex flex-col bg-muted/30 dark:bg-muted/10 rounded-lg border border-muted p-5">
                        <div className="flex items-center gap-3 mb-3">
                          <div className="rounded-full bg-primary/10 p-2">
                            <KeyRound className="h-5 w-5 text-primary" />
                          </div>
                          <h3 className="font-medium text-foreground">
                            You already have an API key
                          </h3>
                        </div>
                        <div className="flex flex-wrap gap-3 mt-1">
                          <Button
                            onClick={skipTokenGeneration}
                            className="bg-primary hover:bg-primary/90 text-primary-foreground font-medium"
                          >
                            Continue with existing key
                          </Button>
                          <Button
                            variant="outline"
                            className="border-border hover:bg-accent text-foreground font-medium"
                            onClick={() => {
                              setShowKeyGeneration(true)
                              setActiveInitStep(1)
                            }}
                          >
                            Generate new key
                          </Button>
                        </div>
                      </div>
                    </div>
                  )}

                  {(!hasExistingApiKey || showKeyGeneration) && (
                    <div
                      className={`transition-all duration-300 ease-in-out ${!showKeyGeneration && hasExistingApiKey ? "opacity-0 h-0 overflow-hidden" : "opacity-100"}`}
                    >
                      {hasExistingApiKey && (
                        <button
                          onClick={() => setShowKeyGeneration(false)}
                          className="flex items-center text-sm text-muted-foreground hover:text-foreground mb-4 transition-colors font-medium"
                        >
                          <ChevronLeft className="h-4 w-4 mr-1" />
                          Back to using existing key
                        </button>
                      )}

                      <div className="flex flex-col space-y-4">
                        <div>
                          <label htmlFor="api-key-name" className="block text-sm font-medium mb-1">
                            API Key Name <span className="text-red-500">*</span>
                          </label>
                          <div className="flex space-x-2">
                            <input
                              id="api-key-name"
                              type="text"
                              placeholder="e.g., Development Key"
                              className={`flex-1 border ${
                                apiKeyState.error ? "border-red-500" : "border-input"
                              } bg-background text-foreground rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-0`}
                              value={apiKeyState.name}
                              onChange={e => setApiKeyName(e.target.value)}
                              required
                            />
                            <Button
                              onClick={handleGenerateApiKey}
                              variant="outline"
                              disabled={generatingKey}
                              className="border-amber-200 bg-amber-50 hover:bg-amber-100 text-amber-800 font-medium"
                            >
                              {generatingKey ? (
                                <>
                                  <span className="animate-spin mr-2">⟳</span>
                                  Generating...
                                </>
                              ) : (
                                <>
                                  <KeyRound className="w-4 h-4 mr-2" />
                                  Generate API Key
                                </>
                              )}
                            </Button>
                          </div>
                          {apiKeyState.error && (
                            <p className="text-red-500 text-xs mt-1 font-medium">
                              {apiKeyState.error}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="space-y-5">
                  <p className="text-sm text-muted-foreground font-medium">
                    Create an API key to authenticate your Codeflash requests
                  </p>

                  <div className="px-4 py-3 border rounded-md border-muted bg-muted/20">
                    <p className="text-sm text-muted-foreground font-medium">
                      Paste this key when{" "}
                      <code className="px-1 py-0.5 bg-muted rounded">codeflash init</code> prompts
                      you for it. You won&apos;t be able to see it again.
                    </p>
                  </div>

                  <div className="space-y-1">
                    <ApiKeyCard label="API Key" value={apiKeyState.key} />
                  </div>

                  <div className="mt-4">
                    <p className="text-sm text-muted-foreground mb-2 font-medium">
                      <strong>Alternatively:</strong> You can also save it in the{" "}
                      <code className="px-1 py-0.5 bg-muted rounded">~/.zshrc</code> or{" "}
                      <code className="px-1 py-0.5 bg-muted rounded">~/.bashrc</code> file.
                    </p>
                    <ApiKeyCard
                      label="Environment Variable"
                      value={`export CODEFLASH_API_KEY='${apiKeyState.key}'`}
                    />
                    {showNewKeyMessage && (
                      <p className="text-xs text-muted-foreground mt-2 font-medium">
                        You can also create new keys later on after this setup
                      </p>
                    )}
                  </div>
                </div>
              )}
            </StepInstruction>
            <StepInstruction
              number={2}
              title="Run the initialization command"
              status={
                activeInitStep === 2 ? "active" : activeInitStep > 2 ? "completed" : "default"
              }
            >
              <p className="text-sm text-muted-foreground mb-3 font-medium">
                Start by running this command in your project&apos;s directory where the
                pyproject.toml file exists
              </p>
              <ApiKeyCard
                label="Terminal"
                value="codeflash init"
                onCopied={() => {
                  if (activeInitStep === 2) {
                    setActiveInitStep(3)
                  }
                }}
              />
            </StepInstruction>
            <StepInstruction
              number={3}
              title="Connect with GitHub"
              status={
                activeInitStep === 3 ? "active" : activeInitStep > 3 ? "completed" : "default"
              }
            >
              <div className="space-y-4">
                <div className="flex items-start space-x-2">
                  <div className="bg-amber-100 p-2 rounded-md">
                    <AlertCircle className="h-5 w-5 text-amber-600" />
                  </div>
                  <p className="text-sm text-muted-foreground font-medium">
                    <span className="font-medium text-foreground">Install the GitHub App:</span>{" "}
                    Codeflash requires this integration to open pull requests with the optimizations
                    for your review.
                  </p>
                </div>
                <div className="flex flex-col items-center space-y-4 pt-2">
                  <Button
                    className="bg-[#24292f] hover:bg-[#0d1117] text-white transition-colors duration-200 w-auto px-6 py-5 font-medium"
                    onClick={() => {
                      window.open(
                        "https://github.com/apps/codeflash-ai/installations/select_target",
                        "_blank",
                      )

                      if (activeInitStep === 3) {
                        setActiveInitStep(4)
                      }
                    }}
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="18"
                      height="18"
                      viewBox="0 0 24 24"
                      fill="white"
                      className="mr-2"
                    >
                      <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
                    </svg>
                    Install GitHub App
                  </Button>
                </div>
              </div>
            </StepInstruction>
          </div>
        </div>
      )
    case "usageInstructions":
      return (
        <div className="w-full space-y-6 relative">
          {/* Celebration header with simple animation */}
          <div className="text-center mb-8 relative">
            {/* Simple glow effect */}
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 bg-primary/10 rounded-full blur-lg -z-10"></div>

            {/* Clean trophy icon with subtle animation */}
            <div className="inline-block mb-6 relative">
              <div className="flex items-center justify-center p-4 bg-gradient-to-b from-primary/20 to-transparent rounded-full shadow-sm relative">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="w-12 h-12 text-primary"
                >
                  <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"></path>
                  <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"></path>
                  <path d="M4 22h16"></path>
                  <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"></path>
                  <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"></path>
                  <path d="M9 2v7.5"></path>
                  <path d="M15 2v7.5"></path>
                  <path d="M12 12a4 4 0 0 0 4-4V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v4a4 4 0 0 0 4 4Z"></path>
                </svg>
              </div>
            </div>

            {/* Celebratory heading */}
            <h3 className="text-2xl font-bold mb-3 text-primary">🎉 Setup Complete! 🎉</h3>
            <div className="bg-primary/5 p-4 rounded-lg max-w-md mx-auto">
              <p className="text-muted-foreground font-medium">
                You&apos;ve successfully set up Codeflash. Here are some commands to get you
                started:
              </p>
            </div>
          </div>

          {/* Command cards with clean styling */}
          <div className="space-y-4 max-w-2xl mx-auto">
            {/* Optimize all code */}
            <div className="bg-card p-5 rounded-lg border border-border hover:border-primary/40 transition-all duration-300 shadow-sm">
              <h4 className="font-medium mb-3 flex items-center">
                <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="text-primary"
                  >
                    <path d="m8 3 4 8 5-5 5 15H2L8 3z"></path>
                  </svg>
                </div>
                Optimize all your code
              </h4>
              <ApiKeyCard label="Optimize All Command" value="codeflash --all" />
            </div>

            {/* Optimize workflow */}
            <div className="bg-card p-5 rounded-lg border border-border hover:border-primary/40 transition-all duration-300 shadow-sm">
              <h4 className="font-medium mb-3 flex items-center">
                <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="text-primary"
                  >
                    <circle cx="12" cy="12" r="10"></circle>
                    <path d="m8 12 3 3 5-5"></path>
                  </svg>
                </div>
                Optimize workflow
              </h4>
              <ApiKeyCard label="Workflow Command" value="codeflash optimize benchmark.py" />
            </div>

            {/* VS Code Extension */}
            <div className="bg-card p-5 rounded-lg border border-border hover:border-primary/40 transition-all duration-300 shadow-sm">
              <h4 className="font-medium mb-3 flex items-center">
                <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="text-primary"
                  >
                    <rect width="18" height="18" x="3" y="3" rx="2" ry="2"></rect>
                    <path d="M9 9h6v6H9z"></path>
                  </svg>
                </div>
                Install VS Code Extension
                <span className="ml-2 text-xs bg-amber-500/10 text-amber-600 dark:text-amber-500 px-2 py-0.5 rounded font-medium">
                  Beta
                </span>
              </h4>
              <p className="text-sm text-muted-foreground mb-3 font-medium">
                Get Codeflash directly in your VS Code editor for a seamless development experience
              </p>
              <a
                href="https://marketplace.visualstudio.com/items?itemName=codeflash.codeflash"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 text-sm text-primary hover:text-primary/80 font-medium"
              >
                Install from VS Code Marketplace
                <ExternalLink className="w-4 h-4" />
              </a>
            </div>

            {/* Setup GitHub Actions */}
            <div className="bg-card p-5 rounded-lg border border-border hover:border-primary/40 transition-all duration-300 shadow-sm">
              <h4 className="font-medium mb-3 flex items-center">
                <div className="flex items-center justify-center p-1.5 bg-primary/10 rounded-md mr-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="text-primary"
                  >
                    <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
                  </svg>
                </div>
                Set up GitHub Actions
              </h4>
              <ApiKeyCard label="GitHub Actions Setup" value="codeflash init-actions" />
              <p className="mt-2 text-sm text-muted-foreground font-medium">
                Automate optimization of your future code by setting up Codeflash Github Actions{" "}
              </p>
            </div>
          </div>
        </div>
      )
    default:
      return <div className="text-center">Content for this step is not available</div>
  }
}
