'use client'

import { useEffect, useState } from 'react'
import { AxiosError, HttpStatusCode } from 'axios'
import * as yup from 'yup'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { useRouter, useSearchParams } from 'next/navigation'
import { Alert, Button, HelperText, Label, TextInput } from 'flowbite-react'

import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'
import { authApi } from '@/lib/utils/api'
import { useAuth } from '@/lib/context/AuthContext'

const formSchema = yup.object({
  email: yup
    .string()
    .email('Invalid email address')
    .required('Email is required'),
  password: yup
    .string()
    .min(8, 'Password must be at least 8 characters long')
    .required('Password is required'),
  password_confirmation: yup
    .string()
    .oneOf([yup.ref('password')], 'Passwords must match')
    .required('Password confirmation is required'),
})

export default function Form() {
  const [processing, setProcessing] = useState(false)
  const [success, setSuccess] = useState(false)
  const [redirectCountdown, setRedirectCountdown] = useState(3)
  const searchParams = useSearchParams()
  const { getCrsfToken } = useAuth()
  const router = useRouter()
  const token = searchParams.get('token')

  const {
    register,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      email: '',
      password: '',
      password_confirmation: '',
    },
  })

  async function handleResetPassword(data: yup.InferType<typeof formSchema>) {
    try {
      setProcessing(true)

      await getCrsfToken()

      await authApi.post('/partner/reset-password', {
        email: data.email,
        password: data.password,
        password_confirmation: data.password_confirmation,
        token: token ?? '',
      })

      setError('root', {
        type: 'manual',
        message: '',
      })

      reset()
      setSuccess(true)
    } catch (e) {
      if (e instanceof AxiosError && e.response) {
        const {
          errors,
          status,
        }: {
          status: string
          errors: Record<keyof yup.InferType<typeof formSchema>, string[]>
        } = e.response.data

        Object.entries(errors ?? []).forEach(([key, message]) => {
          setError(key as keyof yup.InferType<typeof formSchema>, {
            type: 'manual',
            message: message[0],
          })
        })

        if (status && e.status === HttpStatusCode.BadRequest) {
          setError('root', {
            type: 'manual',
            message: status,
          })
        }

        return
      }

      setError('root', {
        type: 'manual',
        message: 'Oops! Something went wrong. Please try again later.',
      })
    } finally {
      setProcessing(false)
    }
  }

  useEffect(() => {
    if (!success) return

    if (redirectCountdown === 0) {
      router.push('/login')
      return
    }

    const timer = setTimeout(() => {
      setRedirectCountdown((prev) => prev - 1)
    }, 1000)

    return () => clearTimeout(timer)
  }, [success, redirectCountdown, router])

  return (
    <form onSubmit={handleSubmit(handleResetPassword)}>
      <div>
        <h1 className="text-3xl font-semibold text-slate-800 mb-3 text-center">
          Reset Password
        </h1>
      </div>

      {!token && (
        <Alert color="failure" className="mt-4">
          Invalid or missing reset token. Please{' '}
          <a
            href="/forgot-password"
            className="font-medium underline hover:text-red-800"
          >
            request a new password reset link
          </a>
          .
        </Alert>
      )}

      {success && (
        <Alert color="success" className="mt-4">
          Your password has been successfully reset. Redirecting to login in{' '}
          {redirectCountdown} second{redirectCountdown !== 1 ? 's' : ''}...
        </Alert>
      )}

      {errors.root?.message && (
        <Alert
          color="failure"
          className="mt-4"
          onDismiss={() => {
            setError('root', {
              type: 'manual',
              message: '',
            })
          }}
        >
          {errors.root?.message}
        </Alert>
      )}

      <div className="space-y-5 mt-10">
        {/* Email Address */}
        <div>
          <div className="mb-2 block text-left">
            <Label htmlFor="email" theme={formTheme.label}>
              Email Address
            </Label>
          </div>
          <TextInput
            id="email"
            type="email"
            placeholder="Enter your email address..."
            theme={formTheme.textInput}
            {...register('email')}
          />
          <HelperText color="failure">{errors.email?.message}</HelperText>
        </div>

        {/* Password */}
        <div>
          <div className="mb-2 block text-left">
            <Label htmlFor="password" theme={formTheme.label}>
              Password
            </Label>
          </div>
          <TextInput
            id="password"
            type="password"
            placeholder="Enter your password..."
            theme={formTheme.textInput}
            {...register('password')}
          />
          <HelperText color="failure">{errors.password?.message}</HelperText>
        </div>

        <div>
          <div className="mb-2 block text-left">
            <Label htmlFor="password_confirmation" theme={formTheme.label}>
              Confirm Password
            </Label>
          </div>
          <TextInput
            id="password_confirmation"
            type="password"
            placeholder="Confirm your password..."
            theme={formTheme.textInput}
            {...register('password_confirmation')}
          />
          <HelperText color="failure">
            {errors.password_confirmation?.message}
          </HelperText>
        </div>
      </div>

      <div className="mt-8">
        <Button
          type="submit"
          theme={buttonTheme.button}
          className="mt-6 w-full"
          disabled={processing || !token || success}
        >
          Reset Password
        </Button>
      </div>

      <div className="mt-4 text-center">
        <a
          href="/login"
          className="text-sm text-blue-600 hover:text-blue-800 hover:underline"
        >
          Back to Login
        </a>
      </div>
    </form>
  )
}
