"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 { useAuth } from "@/hooks/use-auth"
import Image from "next/image"
import Link from "next/link"

export default function UserVerifyOTPPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const toast = useToast()
  const { refreshAuth } = useAuth()

  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 email = searchParams?.get('email') || ""
  const userId = searchParams?.get('userId') || ""

  const inputRefs = useRef<(HTMLInputElement | 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])

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

  const handleInputChange = (index: number, value: string) => {
    // Only allow numeric input
    const numericValue = value.replace(/\D/g, '')

    // Handle multiple characters (paste scenario or rapid typing)
    if (numericValue.length > 1) {
      const digits = numericValue.slice(0, 6)
      const newOtp = [...otp]

      // Fill from current index onwards
      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 filled one - synchronous focus
      const lastFilledIndex = Math.min(index + digits.length - 1, 5)
      const nextEmptyIndex = newOtp.findIndex((digit, i) => !digit && i > lastFilledIndex)
      const nextFocusIndex = nextEmptyIndex !== -1 ? nextEmptyIndex : Math.min(lastFilledIndex + 1, 5)

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

    // Handle single character
    if (numericValue) {
      // Replace current digit with the new one
      const newOtp = [...otp]
      newOtp[index] = numericValue.charAt(0) // Only take first character

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

      // Auto-focus next input if not at the last position - IMMEDIATE FOCUS
      if (index < 5) {
        const nextInput = inputRefs.current[index + 1]
        if (nextInput) {
          // Focus immediately in the same event loop
          nextInput.focus()
          nextInput.select()
        }
      }
    } else if (value === '') {
      // 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]

      // Fill the OTP array with pasted digits
      for (let i = 0; i < pastedData.length && i < 6; i++) {
        newOtp[i] = pastedData[i]
      }

      setOtp(newOtp)
      setError("")

      // Focus the next empty field or the last field if all are filled
      const nextEmptyIndex = newOtp.findIndex(digit => !digit)
      const nextFocusIndex = nextEmptyIndex !== -1 ? nextEmptyIndex : Math.min(pastedData.length, 5)

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

    setIsLoading(true)
    setError("")

    try {
      const response = await DataAPI.auth.verifyUserOTP({
        email,
        otp: otpString
      })

      if (response.success) {
        console.log('OTP Verification successful:', response.data)

        // Refresh auth context to update user state
        console.log('Refreshing auth context...')
        await refreshAuth()
        console.log('Auth context refreshed')

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

        // Redirect to profile completion
        const redirectUrl = `/user/complete-profile?email=${encodeURIComponent(email)}&userId=${userId}`
        console.log('Redirecting to:', redirectUrl)
        router.push(redirectUrl)
      } 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('[User Verify OTP] Already sending, skipping duplicate request')
      return
    }

    setIsResending(true)
    setError("")

    try {
      const response = await DataAPI.auth.resendUserOTP({ email })

      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 {
        setError(response.message || "Failed to resend code")
      }
    } catch (error: any) {
      console.error("Resend OTP error:", error)
      setError(error.message || "Failed to resend code. Please try again.")
    } finally {
      setIsResending(false)
    }
  }

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

  return (
    <div className="min-h-screen bg-gradient-to-b from-white to-muted/30 flex items-center justify-center p-4">
      <div className="w-full max-w-md space-y-6">
        {/* Header */}
        <div className="text-center space-y-2">
          <div className="flex justify-center mb-6">
            <Image
              src="/images/geezer-guide-logo.png"
              alt="Geezer Guide"
              width={220}
              height={110}
              className="h-16 lg:h-20 w-auto drop-shadow-sm"
            />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Verify Your Email</h1>
          <p className="text-gray-600">
            We've sent a 6-digit verification code to{" "}
            <span className="font-medium text-gray-900">{email}</span>
          </p>
        </div>

        {/* OTP Form */}
        <Card>
          <CardHeader className="text-center pb-4">
            <CardTitle className="flex items-center justify-center gap-2 text-lg">
              <Mail className="h-5 w-5 text-blue-600" />
              Enter Verification Code
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* OTP Input */}
            <div className="space-y-2">
              <Label className="text-sm font-medium">Verification Code</Label>
              <div className="flex gap-2 justify-center">
                {otp.map((digit, index) => (
                  <input
                    key={index}
                    ref={(el) => { inputRefs.current[index] = el }}
                    id={`otp-input-${index}`}
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={1}
                    value={digit}
                    onChange={(e) => handleInputChange(index, e.target.value)}
                    onKeyDown={(e) => handleKeyDown(index, e)}
                    onPaste={handlePaste}
                    onFocus={(e) => e.target.select()}
                    className={`w-12 h-12 text-center text-lg font-semibold 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>
            </div>

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

            {/* Completion Status */}
            {isOtpComplete && !error && (
              <div className="text-center">
                <p className="text-sm text-green-600 flex items-center justify-center gap-1">
                  <CheckCircle className="h-4 w-4" />
                  6-digit code entered successfully
                </p>
              </div>
            )}

            {/* Timer */}
            <div className="text-center text-sm text-gray-600">
              Code expires in: <span className="font-mono font-medium">{formatTime(timeLeft)}</span>
            </div>

            {/* Verify Button */}
            <Button
              onClick={handleVerifyOTP}
              disabled={!isOtpComplete || isLoading}
              className="w-full"
              size="lg"
            >
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Verifying...
                </>
              ) : (
                <>
                  <CheckCircle className="mr-2 h-4 w-4" />
                  Verify Email
                </>
              )}
            </Button>

            {/* Resend Code */}
            <div className="text-center">
              <p className="text-sm text-gray-600 mb-2">Didn't receive the code?</p>
              <Button
                variant="ghost"
                onClick={handleResendOTP}
                disabled={!canResend || isResending}
                className="text-blue-600 hover:text-blue-700"
              >
                {isResending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  <>
                    <RefreshCw className="mr-2 h-4 w-4" />
                    Resend Code
                  </>
                )}
              </Button>
              {!canResend && (
                <p className="text-xs text-gray-500 mt-1">
                  You can resend in {formatTime(600 - timeLeft)}
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Back Link */}
        <div className="text-center">
          <Link
            href="/register"
            className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 transition-colors"
          >
            <ArrowLeft className="mr-1 h-4 w-4" />
            Back to Registration
          </Link>
        </div>
      </div>
    </div>
  )
}
