"use client"

import { useState, useEffect, Suspense } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Header } from "@/components/ui/header"
import { Footer } from "@/components/ui/footer"
import { Label } from "@/components/ui/label"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import {
  ShieldCheck,
  ArrowLeft,
  Loader2,
  RefreshCw,
  Clock
} from "lucide-react"
import Link from "next/link"
import { motion } from "framer-motion"

function VerifyOTPContent() {
  const [otp, setOtp] = useState(["", "", "", "", "", ""])
  const [isLoading, setIsLoading] = useState(false)
  const [isResending, setIsResending] = useState(false)
  const [error, setError] = useState("")
  const [timeLeft, setTimeLeft] = useState(600) // 10 minutes
  const [canResend, setCanResend] = useState(false)
  const router = useRouter()
  const searchParams = useSearchParams()
  const toast = useToast()

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

  // Countdown timer
  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) {
          setCanResend(true)
        }
        return newTime
      })
    }, 1000)

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

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

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

    // Handle multiple characters (paste scenario)
    if (numericValue.length > 1) {
      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 - synchronous focus
      const nextEmptyIndex = newOtp.findIndex((digit, i) => !digit && i > index)
      const nextFocusIndex = nextEmptyIndex === -1 ? Math.min(index + digits.length, 5) : nextEmptyIndex

      // Immediate focus
      setTimeout(() => {
        const targetInput = document.getElementById(`otp-${nextFocusIndex}`) as HTMLInputElement
        if (targetInput) {
          targetInput.focus()
          targetInput.select()
        }
      }, 0)
      return
    }

    // Handle single character
    if (numericValue) {
      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 = document.getElementById(`otp-${index + 1}`) as HTMLInputElement
        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 = document.getElementById(`otp-${index - 1}`) as HTMLInputElement
        if (prevInput) {
          prevInput.focus()
          prevInput.select()
        }
      }
    } else if (e.key === 'ArrowLeft' && index > 0) {
      e.preventDefault()
      const prevInput = document.getElementById(`otp-${index - 1}`) as HTMLInputElement
      if (prevInput) {
        prevInput.focus()
        prevInput.select()
      }
    } else if (e.key === 'ArrowRight' && index < 5) {
      e.preventDefault()
      const nextInput = document.getElementById(`otp-${index + 1}`) as HTMLInputElement
      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) {
      return
    }

    const newOtp = [...otp]
    for (let i = 0; i < pastedData.length; i++) {
      newOtp[i] = pastedData[i]
    }
    setOtp(newOtp)
    setError("")

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

    // Focus immediately
    setTimeout(() => {
      const targetInput = document.getElementById(`otp-${nextFocusIndex}`) as HTMLInputElement
      if (targetInput) {
        targetInput.focus()
        targetInput.select()
      }
    }, 0)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    const otpCode = otp.join('')

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

    setIsLoading(true)
    setError("")

    try {
      console.log('Verifying forgot password OTP for:', email)

      const response = await DataAPI.auth.verifyForgotPasswordOTP(email, otpCode)

      console.log('OTP verification response:', response)

      if (response.success && response.data) {
        toast.success("OTP verified successfully. You can now reset your password.", {
          title: "Verified!"
        })

        // Navigate to reset password page
        router.push(`/reset-password?email=${encodeURIComponent(response.data.email)}&token=${response.data.resetToken}`)
      } else {
        throw new Error(response.message || "Invalid OTP")
      }
    } catch (error: any) {
      console.error("OTP verification error:", error)
      setError(error.message || "Invalid OTP. Please try again.")
      toast.error(error.message || "Invalid OTP. Please try again.", {
        title: "Verification Failed"
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleResendOTP = async () => {
    if (!canResend || isResending) return

    setIsResending(true)
    setError("")

    try {
      console.log('Resending forgot password OTP for:', email)

      const response = await DataAPI.auth.resendForgotPasswordOTP(email)

      console.log('Resend OTP response:', response)

      if (response.success) {
        toast.success("A new verification code has been sent to your email.", {
          title: "Code Sent!"
        })

        // Reset timer
        setTimeLeft(600)
        setCanResend(false)
        setOtp(["", "", "", "", "", ""])

        // Focus first input
        const firstInput = document.getElementById('otp-0')
        firstInput?.focus()
      } else {
        throw new Error(response.message || "Failed to resend code")
      }
    } catch (error: any) {
      console.error("Resend OTP error:", error)
      toast.error(error.message || "Failed to resend code. Please try again.", {
        title: "Error"
      })
    } finally {
      setIsResending(false)
    }
  }

  if (!email || !userId) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 flex flex-col">
        <Header />
        <main className="flex-1 flex items-center justify-center px-4">
          <Card className="w-full max-w-md">
            <CardContent className="text-center py-12">
              <p className="text-red-600 mb-4">Invalid request. Missing email or user ID.</p>
              <Link href="/forgot-password">
                <Button>Back to Forgot Password</Button>
              </Link>
            </CardContent>
          </Card>
        </main>
        <Footer />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 flex flex-col">
      <Header />

      <main className="flex-1 flex items-center justify-center px-4 py-12">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="w-full max-w-md"
        >
          <AnimatedCard className="shadow-xl border-t-4 border-t-blue-500">
            <CardHeader className="space-y-4 text-center pb-6">
              <div className="mx-auto w-20 h-20 bg-gradient-to-br from-blue-100 to-blue-50 rounded-full flex items-center justify-center shadow-sm">
                <ShieldCheck className="w-10 h-10 text-blue-600" />
              </div>

              <div className="space-y-2">
                <CardTitle className="text-2xl font-bold text-gray-900 font-primary">
                  Verify Your Identity
                </CardTitle>
                <p className="text-sm text-gray-600 font-body">
                  We've sent a verification code to
                </p>
                <p className="text-sm font-semibold text-blue-600 font-body">
                  {email}
                </p>
                <p className="text-xs text-gray-500 font-body mt-2">
                  Enter the code to reset your password
                </p>
              </div>
            </CardHeader>

            <CardContent className="space-y-6">
              <form onSubmit={handleSubmit} className="space-y-6">
                {/* OTP Input */}
                <div className="space-y-2">
                  <Label className="text-sm font-medium text-gray-700">
                    Verification Code
                  </Label>
                  <div className="flex justify-between gap-2">
                    {otp.map((digit, index) => (
                      <input
                        key={index}
                        id={`otp-${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()}
                        disabled={isLoading}
                        className={`h-14 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'
                          }`}
                        autoFocus={index === 0}
                        autoComplete="one-time-code"
                      />
                    ))}
                  </div>
                  {error && (
                    <p className="text-sm text-red-600 font-body">{error}</p>
                  )}
                </div>

                {/* Timer */}
                <div className="flex items-center justify-center gap-2 text-sm text-gray-600 font-body">
                  <Clock className="w-4 h-4" />
                  <span>Code expires in {formatTime(timeLeft)}</span>
                </div>

                {/* Submit Button */}
                <AnimatedButton
                  type="submit"
                  className="w-full h-12 bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 text-white font-semibold shadow-lg hover:shadow-xl transition-all"
                  disabled={isLoading || otp.some(d => !d)}
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      Verifying...
                    </>
                  ) : (
                    "Verify & Continue"
                  )}
                </AnimatedButton>
              </form>

              {/* Resend Button */}
              <div className="text-center space-y-3">
                <p className="text-sm text-gray-600 font-body">
                  Didn't receive the code?
                </p>
                <Button
                  variant="outline"
                  onClick={handleResendOTP}
                  disabled={isResending || !canResend}
                  className="font-body"
                >
                  {isResending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Sending...
                    </>
                  ) : canResend ? (
                    <>
                      <RefreshCw className="mr-2 h-4 w-4" />
                      Resend Code
                    </>
                  ) : (
                    <>
                      <RefreshCw className="mr-2 h-4 w-4" />
                      Resend in {Math.max(0, 60 - (600 - timeLeft))} seconds
                    </>
                  )}
                </Button>
              </div>

              <div className="text-center">
                <Link
                  href="/login"
                  className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 font-body transition-colors"
                >
                  <ArrowLeft className="w-4 h-4 mr-1" />
                  Back to Sign In
                </Link>
              </div>
            </CardContent>
          </AnimatedCard>
        </motion.div>
      </main>

      <Footer />
    </div>
  )
}

export default function VerifyOTPPage() {
  return (
    <Suspense fallback={<div className="py-20"><span className="inline-block h-6 w-6 rounded-full border-2 border-t-primary border-transparent animate-spin align-middle mr-2" />
      <span className="text-muted-foreground align-middle">Loading…</span></div>}>
      <VerifyOTPContent />
    </Suspense>
  )
}

