"use client"
import React from "react"
import { usePage } from "@inertiajs/react"
import { router } from "@inertiajs/react"
import { useState, useRef } from "react"
import { Input } from "@/Components/UI/Input"
import { Button } from "@/Components/UI/Button"
import AuthLayout from "@/Layouts/AuthLayout"
import { ArrowLeft } from "lucide-react"
import useTranslate from "@/hooks/useTranslate";

export default function VerificationCode() {
  const { errors } = usePage().props
  const [code, setCode] = useState(["", "", "", "", "", ""])
  const [message, setMessage] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const inputRefs = useRef([])

  const t = useTranslate();

  const handleBack = () => {

    window.history.back()
  }

  const handleChange = (e, index) => {
    const { value } = e.target
    if (/^\d*$/.test(value) && value.length <= 1) {
      const newCode = [...code]
      newCode[index] = value
      setCode(newCode)


      if (value && index < 5) {
        inputRefs.current[index + 1].focus()
      }
    }
  }

  const handleKeyDown = (e, index) => {
    if (e.key === "Backspace" && !code[index] && index > 0) {
      inputRefs.current[index - 1].focus()
    }
  }

  const handlePaste = (e) => {
    e.preventDefault()
    const pastedData = e.clipboardData.getData("text").trim()

    if (/^\d+$/.test(pastedData)) {
      const digits = pastedData.split("").slice(0, 6)
      const newCode = [...code]

      digits.forEach((digit, idx) => {
        if (idx < newCode.length) {
          newCode[idx] = digit
        }
      })

      setCode(newCode)

      // focus next empty input if any
      const nextIndex = digits.length < 6 ? digits.length : 5
      if (inputRefs.current[nextIndex]) {
        inputRefs.current[nextIndex].focus()
      }
    }
  }


  const handleSubmit = (e) => {
    e.preventDefault()
    setIsSubmitting(true)
    const fullCode = code.join("")

    const url = route("auth.password.verify.code")
    router.post(url, { otp_code: fullCode }, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  return (
    <AuthLayout>
      <div className="relative">
        {" "}
        {/* Added relative positioning for the arrow */}
        <Button
          variant="ghost"
          size="icon"
          onClick={handleBack}
          className="absolute -top-2 -left-2 text-gray-600 dark:text-gray-200 hover:bg-gray-100"
          aria-label="Go back"
        >
          <ArrowLeft className="h-6 w-6" />
        </Button>
        <h1 className="text-2xl font-bold mb-4 text-center text-gray-700 dark:text-gray-200">{t("Verification Code")}</h1>
        <p className="text-center text-gray-600 dark:text-gray-200 mb-8">{t("Please enter the code we sent to your email")}</p>
        <form onSubmit={handleSubmit}>
          <div className="flex justify-center items-center space-x-2 mb-8">
            {code.map((digit, index) => (
              <React.Fragment key={index}>
                <Input
                  type="text"
                  maxLength="1"
                  value={digit}
                  onChange={(e) => handleChange(e, index)}
                  onKeyDown={(e) => handleKeyDown(e, index)}
                  onPaste={handlePaste}
                  ref={(el) => (inputRefs.current[index] = el)}
                  className="w-12 h-12 text-center text-2xl font-bold border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  inputMode="numeric"
                  pattern="[0-9]"
                  aria-label={`Digit ${index + 1} of verification code`}
                />
                {index === 2 && <span className="lg:text-3xl text-2xl font-bold text-gray-400">-</span>}
              </React.Fragment>
            ))}
          </div>
          <Button
            type="submit"
            isLoading={isSubmitting}
            className="w-full bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-md hover:shadow-lg transition-all duration-200"
          >
            {isSubmitting ? t("Verifying...") : t("Continue")}
          </Button>
        </form>
        {errors.otp_code && (
          <p className={"mt-4 text-center text-sm text-red-600"}>
            {errors.otp_code}
          </p>
        )}
        <p className="mt-4 text-center text-sm text-gray-500">
          {t("Didn't receive a code?")}{" "}
          <a href="#" className="text-primary hover:underline">
            {t("Resend")}
          </a>
        </p>
      </div>
    </AuthLayout>
  )
}
