"use client"

import * as React from "react"
import { useState } from "react"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Eye, EyeOff, ArrowLeft } from "lucide-react"
import Link from "next/link"
import Image from "next/image"
import { cn } from "@/lib/utils"
import { useForgotPassword, useVerifyOtp } from "@/lib/react-query/hooks/auth"
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"
import { PasswordStrengthInput } from "@/components/password-strength-input"
import { useTranslations } from "next-intl"
import { LanguageSwitcher } from "@/components/ui/language-switcher"
import { useLocale } from "next-intl"
import { useSearchParams, useRouter } from "next/navigation"

type Step = "email" | "otp"

export default function ForgotPassword() {
  const t = useTranslations('auth')
  const tv = useTranslations('validation')
  const locale = useLocale()
  const searchParams = useSearchParams()
  const router = useRouter()

  const passwordStrengthTranslations = {
    veryWeak: tv('passwordStrength.veryWeak'),
    weak: tv('passwordStrength.weak'),
    fair: tv('passwordStrength.fair'),
    good: tv('passwordStrength.good'),
    strong: tv('passwordStrength.strong'),
    lowercase: tv('passwordStrength.lowercase'),
    uppercase: tv('passwordStrength.uppercase'),
    number: tv('passwordStrength.number'),
    special: tv('passwordStrength.special'),
    minLength: tv('passwordStrength.minLength')
  }

  // Initialize state from URL params
  React.useEffect(() => {
    const stepParam = searchParams.get('step')
    const emailParam = searchParams.get('email')
    
    if (stepParam === 'otp' && emailParam) {
      setStep('otp')
      setEmail(emailParam)
    }
  }, [searchParams])
  const [step, setStep] = useState<Step>("email")
  const [email, setEmail] = useState("")
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  const forgotPasswordMutation = useForgotPassword()
  const verifyOtpMutation = useVerifyOtp()

  // Email step schema
  const emailSchema = z.object({
    email: z.string().email(tv('invalidEmail'))
  })

  // OTP step schema
  const otpSchema = z.object({
    otp: z.string().length(6, tv('otpRequired')),
    newPassword: z.string()
      .min(6, tv('passwordTooShort'))
      .regex(/[a-z]/, tv('passwordLowercase'))
      .regex(/[A-Z]/, tv('passwordUppercase'))
      .regex(/\d/, tv('passwordNumber'))
      .regex(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/, tv('passwordSpecial')),
    confirmPassword: z.string().min(6, tv('confirmPasswordRequired'))
  }).refine((data) => data.newPassword === data.confirmPassword, {
    message: tv('passwordMismatch'),
    path: ["confirmPassword"]
  })

  type EmailFormValues = z.infer<typeof emailSchema>
  type OtpFormValues = z.infer<typeof otpSchema>

  const emailForm = useForm<EmailFormValues>({
    resolver: zodResolver(emailSchema),
    defaultValues: { email: "" }
  })

  const otpForm = useForm<OtpFormValues>({
    resolver: zodResolver(otpSchema),
    defaultValues: { otp: "", newPassword: "", confirmPassword: "" }
  })

  const onEmailSubmit = async (values: EmailFormValues) => {
    await forgotPasswordMutation.mutateAsync({ email: values.email })
    setEmail(values.email)
    setStep("otp")
    // Update URL with step and email params
    router.push(`/${locale}/forgot-password?step=otp&email=${encodeURIComponent(values.email)}`)
  }

  const onOtpSubmit = async (values: OtpFormValues) => {
    await verifyOtpMutation.mutateAsync({
      email,
      otp: values.otp,
      newPassword: values.newPassword
    })
  }

  const handleBackToEmail = () => {
    setStep("email")
    setEmail("")
    otpForm.reset()
    // Clear URL params
    router.push(`/${locale}/forgot-password`)
  }

  return (
    <div className="min-h-screen w-full flex flex-col justify-center items-center bg-white px-4 py-8 sm:px-8 relative">
      {/* Language Switcher */}
      <div className="absolute top-4 right-4">
        <LanguageSwitcher />
      </div>
      <div className="w-full max-w-xl">
        {/* LOGO + TITLE */}
        <div className="flex flex-col items-center gap-3 mb-6">
          <Link href="/" className="flex items-center">
            <Image src="/aivly-logo.svg" alt="Company Logo" width={200} height={50} priority />
          </Link>
          <h1 className="text-[26px] sm:text-[32px] font-semibold text-foreground text-center">
            {step === "email" ? t('forgotPassword').replace('?', '') : t('resetPassword')}
          </h1>
          <p className="text-gray-600 text-center">
            {step === "email" 
              ? t('forgotPasswordDesc')
              : t('resetPasswordDesc').replace('your email', email)
            }
          </p>
        </div>

        {/* Step 1: Email Form */}
        {step === "email" && (
          <Form {...emailForm}>
            <form onSubmit={emailForm.handleSubmit(onEmailSubmit)} className="space-y-5 sm:space-y-6">
              <FormField
                control={emailForm.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t('email')}</FormLabel>
                    <FormControl>
                      <Input placeholder={t('email')} {...field} className="h-12 sm:h-14 text-base" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="pt-4 space-y-5">
                <Button 
                  disabled={forgotPasswordMutation.isPending} 
                  type="submit" 
                  className="w-full h-12 sm:h-14 text-lg font-medium bg-primary-gradient hover:opacity-90"
                >
                  {forgotPasswordMutation.isPending ? t('sendingOTP') : t('sendOTP')}
                </Button>

                <p className="text-center text-base text-gray-600">
                  {t('rememberPassword')}{" "}
                  <Link href={`/${locale}/sign-in`} className="font-semibold text-primary underline">
                    {t('login')}
                  </Link>
                </p>
              </div>
            </form>
          </Form>
        )}

        {/* Step 2: OTP + New Password Form */}
        {step === "otp" && (
          <Form {...otpForm}>
            <form onSubmit={otpForm.handleSubmit(onOtpSubmit)} className="space-y-5 sm:space-y-6">
              {/* Back button */}
              <Button
                type="button"
                variant="ghost"
                onClick={handleBackToEmail}
                className="flex items-center gap-2 p-0 h-auto text-gray-600 hover:text-gray-900"
              >
                <ArrowLeft className="w-4 h-4" />
                {t('changeEmail')}
              </Button>

              {/* OTP Input */}
              <FormField
                control={otpForm.control}
                name="otp"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t('enterOTP')}</FormLabel>
                    <FormControl>
                      <InputOTP maxLength={6} value={field.value} onChange={field.onChange}>
                        <InputOTPGroup className="gap-2 w-full justify-center">
                          <InputOTPSlot index={0} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                          <InputOTPSlot index={1} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                          <InputOTPSlot index={2} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                          <InputOTPSlot index={3} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                          <InputOTPSlot index={4} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                          <InputOTPSlot index={5} className="h-12 w-12 sm:h-14 sm:w-14 text-lg" />
                        </InputOTPGroup>
                      </InputOTP>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* New Password */}
              <FormField
                control={otpForm.control}
                name="newPassword"
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel>{t('newPassword')}</FormLabel>
                    <FormControl>
                      <PasswordStrengthInput
                        value={field.value}
                        onChange={field.onChange}
                        placeholder={t('newPassword')}
                        className={fieldState?.error ? "border-destructive focus-visible:ring-destructive/40" : ""}
                        translations={passwordStrengthTranslations}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Confirm Password */}
              <FormField
                control={otpForm.control}
                name="confirmPassword"
                render={({ field, fieldState }) => (
                  <FormItem>
                    <FormLabel>{t('confirmPassword')}</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          type={showConfirmPassword ? "text" : "password"}
                          placeholder={t('confirmPassword')}
                          {...field}
                          className={cn(
                            "h-12 sm:h-14 text-base pr-12 w-full",
                            fieldState?.error && "border-destructive focus-visible:ring-destructive/40"
                          )}
                        />
                        <button
                          type="button"
                          onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                          className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500"
                        >
                          {showConfirmPassword ? <Eye className="w-5 h-5" /> : <EyeOff className="w-5 h-5" />}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="pt-4 space-y-5">
                <Button 
                  disabled={verifyOtpMutation.isPending} 
                  type="submit" 
                  className="w-full h-12 sm:h-14 text-lg font-medium bg-primary-gradient hover:opacity-90"
                >
                  {verifyOtpMutation.isPending ? t('resettingPassword') : t('resetPassword')}
                </Button>

                <p className="text-center text-base text-gray-600">
                  {t('didntReceiveOTP')}{" "}
                  <button
                    type="button"
                    onClick={() => forgotPasswordMutation.mutate({ email })}
                    disabled={forgotPasswordMutation.isPending}
                    className="font-semibold text-primary underline"
                  >
                    {t('resendOTP')}
                  </button>
                </p>
              </div>
            </form>
          </Form>
        )}
      </div>
    </div>
  )
}
