"use client"

import LogoBox from "@/components/dashboard/logo-box"
import Image from "next/image"
import { useState, useEffect, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Loading } from "@/components/ui/loading"
import {
  authorizeOAuth,
  createOAuthState,
  fetchUserOrganizations,
  fetchUserInfo,
  storeOAuthParams,
  getStoredOAuthParams,
  Organization,
  UserInfo,
} from "./action"

export default function CodeFlashAuthContent() {
  const [isLoading, setIsLoading] = useState(false)
  const [isCheckingAuth, setIsCheckingAuth] = useState(true)
  const [error, setError] = useState<string | null>(null)
  type AuthStep = "checking" | "ready" | "authorizing" | "waiting"
  const [step, setStep] = useState<AuthStep>("checking")
  const [hasAuthenticated, setHasAuthenticated] = useState(false)
  const [theme, setTheme] = useState<"light" | "dark">("light")
  const [organizations, setOrganizations] = useState<Organization[]>([])
  const [selectedOrgId, setSelectedOrgId] = useState<string>("")
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null)
  const searchParams = useSearchParams()
  const router = useRouter()

  // Extract individual params as stable string primitives for dependency array
  const responseType = searchParams.get("response_type")
  const clientId = searchParams.get("client_id")
  const redirectUri = searchParams.get("redirect_uri")
  const codeChallenge = searchParams.get("code_challenge")
  const codeChallengeMethod = searchParams.get("code_challenge_method")
  const state = searchParams.get("state")

  // Detect theme on mount and when it changes
  useEffect(() => {
    const detectTheme = () => {
      const isDark = document.documentElement.classList.contains("dark")
      setTheme(isDark ? "dark" : "light")
    }

    // Initial detection
    detectTheme()

    // Watch for theme changes
    const observer = new MutationObserver(detectTheme)
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ["class"],
    })

    return () => observer.disconnect()
  }, [])

  const hasCheckedAuth = useRef(false)

  useEffect(() => {
    // Guard against duplicate runs (React Strict Mode, Suspense remounts)
    if (hasCheckedAuth.current) return
    hasCheckedAuth.current = true

    const checkAuth = async () => {
      setStep("checking")
      try {
        const allowedClients = ["cf_vscode_app", "cf-cli-app"]

        if (responseType !== "code") {
          setError("Invalid request parameters")
          return
        }

        if (!clientId || !allowedClients.includes(clientId)) {
          setError("Invalid client application")
          return
        }

        if (!redirectUri) {
          setError("Invalid redirect destination")
          return
        }

        if (!codeChallenge || !codeChallengeMethod) {
          setError("Missing security parameters")
          return
        }

        if (!state) {
          setError("Missing request identifier")
          return
        }

        // Fetch user info and organizations
        const [userResult, orgsResult] = await Promise.all([
          fetchUserInfo(),
          fetchUserOrganizations(),
        ])

        if (userResult.error === "Unauthorized") {
          const currentUrl = window.location.pathname + window.location.search
          router.replace(`/login?returnTo=${encodeURIComponent(currentUrl)}`)
          return
        }

        if (userResult.user) {
          setUserInfo(userResult.user)
        }
        if (orgsResult.organizations) {
          setOrganizations(orgsResult.organizations)
        }

        // Store OAuth params in server-side HttpOnly cookie
        const storeResult = await storeOAuthParams({
          redirectUri,
          codeChallenge,
          codeChallengeMethod,
          clientId,
          vscodeState: state,
        })

        if (storeResult.error) {
          setError(storeResult.error)
          return
        }

        setStep("ready")
      } catch {
        setError("An unexpected error occurred. Please try again.")
      } finally {
        setIsCheckingAuth(false)
      }
    }

    checkAuth()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const handleAuthenticate = async () => {
    // Prevent multiple authentications
    if (hasAuthenticated) {
      return
    }

    setIsLoading(true)
    setError(null)
    setStep("authorizing")

    try {
      // Retrieve OAuth params from server-side HttpOnly cookie
      const stored = await getStoredOAuthParams()
      if (stored.error || !stored.params) {
        setError(stored.error || "Session expired. Please refresh the page and try again.")
        setIsLoading(false)
        setStep("ready")
        return
      }

      const { redirectUri, codeChallenge, codeChallengeMethod, clientId, vscodeState } =
        stored.params

      // Create OAuth state with selected org
      const stateResult = await createOAuthState({
        redirectUri,
        codeChallenge,
        codeChallengeMethod,
        clientId,
        orgId: selectedOrgId || undefined,
      })

      if (stateResult.error) {
        setError(
          stateResult.error === "Rate limit exceeded"
            ? "Too many authentication attempts. Please try again later."
            : "An error occurred. Please try again.",
        )
        setIsLoading(false)
        setStep("ready")
        return
      }

      const result = await authorizeOAuth(stateResult.state)

      if (result.error) {
        setError(
          result.error === "Rate limit exceeded"
            ? "Too many authentication attempts. Please try again later."
            : "Authentication failed. Please try again.",
        )
        setIsLoading(false)
        setStep("ready")
        return
      }

      if (!result.code || !result.redirectUri) {
        setError("Authentication failed. Please try again.")
        setIsLoading(false)
        setStep("ready")
        return
      }

      setHasAuthenticated(true)

      // Redirect back to VS Code with code, state, and theme
      const redirectUrl = new URL(result.redirectUri)
      redirectUrl.searchParams.set("code", result.code)
      redirectUrl.searchParams.set("state", vscodeState)
      redirectUrl.searchParams.set("theme", theme)

      setStep("waiting")
      setIsLoading(false)

      window.location.href = redirectUrl.toString()
    } catch {
      setError("An error occurred. Please try again.")
      setIsLoading(false)
      setStep("ready")
    }
  }

  if (isCheckingAuth || step === "checking") {
    return <Loading />
  }

  function getInitials(name: string): string {
    return name
      .split(" ")
      .map(n => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2)
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="min-h-screen flex flex-col items-center justify-center px-4 py-12">
        <div className="mb-8">
          <LogoBox />
        </div>

        <div className="w-full max-w-[400px]">
          {error ? (
            <div className="bg-card border border-border rounded-lg p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-destructive/10 flex items-center justify-center">
                  <svg
                    className="w-5 h-5 text-destructive"
                    fill="none"
                    strokeWidth="2"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
                    />
                  </svg>
                </div>
                <div>
                  <h2 className="text-base font-semibold text-foreground">Authentication Error</h2>
                  <p className="text-sm text-muted-foreground">{error}</p>
                </div>
              </div>
            </div>
          ) : (
            <div className="bg-card border border-border rounded-lg overflow-hidden">
              {/* Header */}
              <div className="px-4 py-3 border-b border-border">
                <h1 className="text-sm font-semibold text-foreground">Authorize Codeflash</h1>
                <p className="text-xs text-muted-foreground mt-0.5">
                  Select an account to continue to Codeflash CLI
                </p>
              </div>

              {/* Account List */}
              <div className="divide-y divide-border">
                {/* Personal Account */}
                <button
                  type="button"
                  onClick={() => setSelectedOrgId("")}
                  className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${
                    selectedOrgId === "" ? "bg-primary/5" : "hover:bg-muted/50"
                  }`}
                >
                  {userInfo?.avatarUrl ? (
                    <Image
                      src={userInfo.avatarUrl}
                      alt={userInfo.name}
                      width={32}
                      height={32}
                      className="w-8 h-8 rounded-full"
                      unoptimized
                    />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white text-xs font-medium">
                      {getInitials(userInfo?.name || "User")}
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-foreground truncate">
                      {userInfo?.name || "Personal Account"}
                    </div>
                    {userInfo?.email && (
                      <div className="text-xs text-muted-foreground truncate">{userInfo.email}</div>
                    )}
                  </div>
                  <div
                    className={`w-4 h-4 rounded-full border-2 flex items-center justify-center transition-colors ${
                      selectedOrgId === ""
                        ? "border-primary bg-primary"
                        : "border-muted-foreground/30"
                    }`}
                  >
                    {selectedOrgId === "" && <div className="w-1.5 h-1.5 rounded-full bg-white" />}
                  </div>
                </button>

                {/* Organizations */}
                {organizations.map(org => (
                  <button
                    key={org.id}
                    type="button"
                    onClick={() => setSelectedOrgId(org.id)}
                    className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${
                      selectedOrgId === org.id ? "bg-primary/5" : "hover:bg-muted/50"
                    }`}
                  >
                    {org.avatarUrl ? (
                      <Image
                        src={org.avatarUrl}
                        alt={org.name}
                        width={32}
                        height={32}
                        className="w-8 h-8 rounded-md"
                        unoptimized
                      />
                    ) : (
                      <div className="w-8 h-8 rounded-md bg-gradient-to-br from-orange-500 to-red-600 flex items-center justify-center text-white text-xs font-medium">
                        {getInitials(org.name)}
                      </div>
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-foreground truncate">{org.name}</div>
                      <div className="text-xs text-muted-foreground">Organization</div>
                    </div>
                    <div
                      className={`w-4 h-4 rounded-full border-2 flex items-center justify-center transition-colors ${
                        selectedOrgId === org.id
                          ? "border-primary bg-primary"
                          : "border-muted-foreground/30"
                      }`}
                    >
                      {selectedOrgId === org.id && (
                        <div className="w-1.5 h-1.5 rounded-full bg-white" />
                      )}
                    </div>
                  </button>
                ))}
              </div>

              {/* Footer with Authorize Button */}
              <div className="px-4 py-3 bg-muted/30 border-t border-border">
                <button
                  onClick={handleAuthenticate}
                  disabled={isLoading || hasAuthenticated}
                  className="w-full h-9 px-4 bg-primary hover:bg-primary/90 text-primary-foreground text-sm font-medium rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {isLoading ? (
                    <>
                      <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                        <circle
                          className="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          strokeWidth="4"
                        />
                        <path
                          className="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                        />
                      </svg>
                      Authenticating...
                    </>
                  ) : (
                    "Authenticate"
                  )}
                </button>
                <p className="text-[11px] text-muted-foreground text-center mt-2">
                  Codeflash requires authentication to associate Codeflash CLI or Codeflash
                  extension on your machine.
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
