"use client"

import { useState, useEffect, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { ArrowLeft, Mail, RefreshCw, CheckCircle, AlertCircle, Loader2 } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import Image from "next/image"
import Link from "next/link"

export default function VerifyOTPPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const toast = useToast()

  const [otp, setOtp] = useState(["", "", "", "", "", ""])
  const [isLoading, setIsLoading] = useState(false)
  const [isResending, setIsResending] = useState(false)
  const [timeLeft, setTimeLeft] = useState(600) // 10 minutes
  const [canResend, setCanResend] = useState(false)
  const [error, setError] = useState("")
  const [hasAutoSent, setHasAutoSent] = useState(false) // Track if we've auto-sent on page load

  const email = searchParams?.get('email') || ""
  const userId = searchParams?.get('userId') || ""

  const inputRefs = useRef<(HTMLInputElement | null)[]>([])
  const hasAutoSentRef = useRef(false) // Use ref to prevent multiple sends even in Strict Mode

  // Debug: Log refs on mount and updates
  useEffect(() => {
    console.log('🔍 [OTP] Component mounted/updated')
    console.log('🔍 [OTP] Input refs array:', inputRefs.current)
    console.log('🔍 [OTP] Number of refs:', inputRefs.current.filter(ref => ref !== null).length)
    inputRefs.current.forEach((ref, idx) => {
      console.log(`🔍 [OTP] Ref[${idx}]:`, ref ? 'EXISTS' : 'NULL')
    })
  })

  // Countdown timer and resend logic
  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        const newTime = prev > 0 ? prev - 1 : 0
        // Allow resend after 1 minute (when 9 minutes are left)
        if (newTime === 540) { // 600 - 60 = 540 seconds left
          setCanResend(true)
        }
        return newTime
      })
    }, 1000)

    return () => clearInterval(timer)
  }, [])

  // Redirect if no email or userId
  useEffect(() => {
    if (!email || !userId) {
      router.push('/register')
    }
  }, [email, userId, router])

  // Automatically send OTP when page loads (if user just signed up)
  // Use ref to prevent multiple sends in React Strict Mode
  useEffect(() => {
    // Only send if we haven't sent yet and have required params
    if (email && userId && !hasAutoSentRef.current && !isResending) {
      console.log('[Verify OTP] Page loaded, automatically sending OTP to:', email)
      hasAutoSentRef.current = true // Mark as sent immediately using ref
      setHasAutoSent(true) // Also update state for UI
      // Auto-send OTP on page load
      handleResendOTP()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []) // Only run once on mount - don't include dependencies that might change

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  const handleOtpChange = (index: number, value: string) => {
    console.log('🔵 [OTP] handleOtpChange called:', { index, value, currentOtp: otp })

    // Only allow numeric input
    const numericValue = value.replace(/\D/g, '')
    console.log('🔵 [OTP] Numeric value after filtering:', numericValue)

    // Handle multiple characters (paste scenario)
    if (numericValue.length > 1) {
      console.log('🔵 [OTP] Multi-character input detected (paste)')
      const digits = numericValue.slice(0, 6)
      const newOtp = [...otp]

      for (let i = 0; i < digits.length && (index + i) < 6; i++) {
        newOtp[index + i] = digits[i]
      }

      setOtp(newOtp)
      setError("")

      // Focus the next empty input or the last one - use synchronous focus
      const nextEmptyIndex = newOtp.findIndex((digit, i) => !digit && i > index)
      const nextFocusIndex = nextEmptyIndex === -1 ? Math.min(index + digits.length, 5) : nextEmptyIndex
      console.log('🔵 [OTP] Will focus on index:', nextFocusIndex)

      // Immediate focus using setTimeout 0
      setTimeout(() => {
        const nextInput = inputRefs.current[nextFocusIndex]
        console.log('🔵 [OTP] Next input element:', nextInput)
        if (nextInput) {
          console.log('✅ [OTP] Calling focus() on next input')
          nextInput.focus()
          nextInput.select()
          console.log('✅ [OTP] Focus called, active element:', document.activeElement)
        } else {
          console.error('❌ [OTP] Next input is null!')
        }
      }, 0)
      return
    }

    // Handle single character
    if (numericValue) {
      console.log('🔵 [OTP] Single character input:', numericValue)
      // Replace current digit with the new one
      const newOtp = [...otp]
      newOtp[index] = numericValue.charAt(0) // Only take first character

      console.log('🔵 [OTP] Updated OTP array:', newOtp)

      // Update state first
      setOtp(newOtp)
      setError("")

      // Auto-focus next input if not at the last position - IMMEDIATE FOCUS
      if (index < 5) {
        console.log('🔵 [OTP] Attempting to focus next box (index:', index + 1, ')')
        const nextInput = inputRefs.current[index + 1]
        console.log('🔵 [OTP] Next input ref:', nextInput)
        console.log('🔵 [OTP] All input refs:', inputRefs.current)

        if (nextInput) {
          console.log('✅ [OTP] Next input exists, calling focus()')
          console.log('🔵 [OTP] Before focus - Active element:', document.activeElement)

          // Focus immediately in the same event loop
          nextInput.focus()
          nextInput.select()

          console.log('✅ [OTP] After focus() called - Active element:', document.activeElement)
          console.log('✅ [OTP] Is next input focused?', document.activeElement === nextInput)
        } else {
          console.error('❌ [OTP] Next input ref is NULL! Cannot focus.')
        }
      } else {
        console.log('🔵 [OTP] Last box - no next input to focus')
      }
    } else if (value === '') {
      console.log('🔵 [OTP] Empty value - clearing current digit')
      // If empty value (deletion), clear current digit
      const newOtp = [...otp]
      newOtp[index] = ''
      setOtp(newOtp)
      setError("")
    }
  }

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === 'Backspace') {
      e.preventDefault()
      const newOtp = [...otp]

      if (otp[index]) {
        // If current field has value, clear it
        newOtp[index] = ''
        setOtp(newOtp)
        setError("")
      } else if (index > 0) {
        // If current field is empty, move to previous field and clear it
        newOtp[index - 1] = ''
        setOtp(newOtp)
        setError("")

        // Focus previous immediately
        const prevInput = inputRefs.current[index - 1]
        if (prevInput) {
          prevInput.focus()
          prevInput.select()
        }
      }
    } else if (e.key === 'ArrowLeft' && index > 0) {
      e.preventDefault()
      const prevInput = inputRefs.current[index - 1]
      if (prevInput) {
        prevInput.focus()
        prevInput.select()
      }
    } else if (e.key === 'ArrowRight' && index < 5) {
      e.preventDefault()
      const nextInput = inputRefs.current[index + 1]
      if (nextInput) {
        nextInput.focus()
        nextInput.select()
      }
    }
  }

  const handlePaste = (e: React.ClipboardEvent) => {
    e.preventDefault()
    const pastedData = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6)

    if (pastedData.length > 0) {
      const newOtp = [...otp]

      for (let i = 0; i < pastedData.length; i++) {
        newOtp[i] = pastedData[i]
      }

      setOtp(newOtp)
      setError("")

      // Focus the next empty input or the last one
      const nextEmptyIndex = newOtp.findIndex(digit => !digit)
      const nextFocusIndex = nextEmptyIndex === -1 ? 5 : nextEmptyIndex

      // Focus immediately
      setTimeout(() => {
        const nextInput = inputRefs.current[nextFocusIndex]
        if (nextInput) {
          nextInput.focus()
          nextInput.select()
        }
      }, 0)
    }
  }

  const handleVerifyOTP = async () => {
    const otpString = otp.join('')

    if (otpString.length !== 6) {
      setError("Please enter the complete 6-digit code")
      return
    }

    console.log('[Verify OTP] Submitting OTP:', {
      email,
      otpLength: otpString.length,
      otp: otpString, // Log in development
      userId
    })

    setIsLoading(true)
    setError("")

    try {
      const response = await DataAPI.auth.verifyOTP({
        email: email.trim().toLowerCase(), // Ensure email is normalized
        otp: otpString
      })

      console.log('[Verify OTP] Response:', response)

      if (response.success) {
        toast.success("Now let's complete your facility profile.", {
          title: "Email Verified!"
        })

        // Redirect to profile completion
        router.push(`/facility/complete-profile?email=${encodeURIComponent(email)}&userId=${userId}`)
      } else {
        setError(response.message || "Invalid verification code")
        setOtp(["", "", "", "", "", ""]) // Clear OTP
        inputRefs.current[0]?.focus()
      }
    } catch (error: any) {
      console.error("OTP verification error:", error)
      setError(error.message || "Verification failed. Please try again.")
      setOtp(["", "", "", "", "", ""])
      inputRefs.current[0]?.focus()
    } finally {
      setIsLoading(false)
    }
  }

  const handleResendOTP = async () => {
    // Prevent multiple simultaneous sends
    if (isResending) {
      console.log('[Verify OTP] Already sending, skipping duplicate request')
      return
    }

    setIsResending(true)
    setError("")

    try {
      console.log('[Verify OTP] Resending OTP to:', email)
      const response = await DataAPI.auth.resendOTP({ email })
      console.log('[Verify OTP] Resend response:', response)

      if (response.success) {
        toast.success("A new verification code has been sent to your email.", {
          title: "Code Sent!"
        })
        setTimeLeft(600) // Reset timer
        setCanResend(false) // Reset resend flag
        setOtp(["", "", "", "", "", ""]) // Clear current OTP
        inputRefs.current[0]?.focus()
      } else {
        const errorMsg = response.message || "Failed to resend code"
        console.error('[Verify OTP] Resend failed:', errorMsg)
        setError(errorMsg)
        toast.error(errorMsg, {
          title: "Failed to Send Code"
        })
      }
    } catch (error: any) {
      console.error("[Verify OTP] Resend OTP error:", error)
      const errorMsg = error.message || "Failed to resend code. Please try again."
      setError(errorMsg)
      toast.error(errorMsg, {
        title: "Error"
      })
    } finally {
      setIsResending(false)
    }
  }

  const isOtpComplete = otp.every(digit => digit !== "")

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-muted/30">
      {/* Header */}
      <header className="border-b border-border bg-white">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <Link href="/register" className="flex items-center space-x-4">
              <ArrowLeft className="h-5 w-5 text-muted-foreground" />
              <Image
                src="/images/geezer-guide-logo.png"
                alt="Geezer Guide"
                width={220}
                height={110}
                className="h-16 lg:h-24 xl:h-28 w-auto drop-shadow-sm"
              />
            </Link>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-12">
        <div className="max-w-md mx-auto">
          <div className="text-center mb-8">
            <div className="mx-auto w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mb-4">
              <Mail className="h-8 w-8 text-blue-600" />
            </div>
            <h1 className="font-heading text-3xl md:text-4xl text-foreground mb-4">
              Verify Your Email
            </h1>
            <p className="font-body text-base md:text-lg text-slate-700 mb-2">
              We've sent a 6-digit verification code to:
            </p>
            <p className="font-body text-lg font-semibold text-blue-600">{email}</p>
          </div>

          <Card>
            <CardHeader>
              <CardTitle className="font-heading text-xl text-center">Enter Verification Code</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* OTP Input */}
              <div className="space-y-4">
                <div className="flex justify-center gap-3">
                  {otp.map((digit, index) => (
                    <input
                      key={index}
                      ref={(el) => {
                        inputRefs.current[index] = el
                        console.log(`🔧 [OTP] Setting ref[${index}]:`, el ? 'ELEMENT SET' : 'NULL')
                      }}
                      id={`otp-input-${index}`}
                      type="text"
                      inputMode="numeric"
                      pattern="[0-9]*"
                      maxLength={1}
                      value={digit}
                      onChange={(e) => handleOtpChange(index, e.target.value)}
                      onKeyDown={(e) => handleKeyDown(index, e)}
                      onPaste={handlePaste}
                      onFocus={(e) => e.target.select()}
                      className={`w-12 h-12 text-center text-xl font-bold border-2 rounded-md focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 transition-all ${error ? 'border-red-500' :
                          digit ? 'border-green-500 bg-green-50' : 'border-gray-300'
                        }`}
                      disabled={isLoading}
                      autoFocus={index === 0}
                      autoComplete="one-time-code"
                    />
                  ))}
                </div>

                {/* Error Message - Now below OTP input */}
                {error && (
                  <Alert variant="destructive">
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}

                <div className="text-center">
                  <p className="text-sm text-slate-600">
                    Code expires in: <span className="font-semibold text-red-600">{formatTime(timeLeft)}</span>
                  </p>
                </div>
              </div>

              {/* Verify Button */}
              <Button
                onClick={handleVerifyOTP}
                disabled={!isOtpComplete || isLoading || timeLeft === 0}
                className="w-full h-12 text-lg bg-blue-600 hover:bg-blue-700 font-body"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Verifying...
                  </>
                ) : (
                  <>
                    <CheckCircle className="mr-2 h-4 w-4" />
                    Verify Code
                  </>
                )}
              </Button>

              {/* Resend Code */}
              <div className="text-center space-y-2">
                <p className="text-sm text-slate-600">Didn't receive the code?</p>
                <Button
                  variant="outline"
                  onClick={handleResendOTP}
                  disabled={isResending}
                  className="font-body"
                >
                  {isResending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    <>
                      <RefreshCw className="mr-2 h-4 w-4" />
                      Resend Code
                    </>
                  )}
                </Button>
                {isResending && (
                  <p className="text-xs text-slate-500">
                    Sending verification code to {email}...
                  </p>
                )}
              </div>

              {/* Help Text */}
              <div className="bg-slate-50 p-4 rounded-lg">
                <p className="text-sm text-slate-700">
                  <strong>Check your spam folder</strong> if you don't see the email.
                  The verification code is valid for 10 minutes.
                </p>
              </div>
            </CardContent>
          </Card>

          <div className="text-center mt-8">
            <p className="font-body text-sm text-slate-600">
              Need help? Email us at{" "}
              <a href="mailto:support@geezerguide.com" className="text-blue-600 hover:underline">
                support@geezerguide.com
              </a>
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
