"use client"

import React from "react"
import { useForm } from "react-hook-form"
import { yupResolver } from "@hookform/resolvers/yup"
import { passwordValidationSchema } from "@/utils/form"
import { toast } from "react-toastify"
import PocketBase from "pocketbase"
import PageWrapper from "@/components/Utilities/PageWrapper"
import { usePathname } from "next/navigation"
import Background from "@/components/Utilities/Background"
import PageHeader from "@/sections/PageHeader"

const pb = new PocketBase(process.env.NEXT_PUBLIC_POCKETBASE_URL)

export default function ConfirmPasswordResetPage() {
  const pathName = usePathname()
  const token = pathName.split("/").at(-1)
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset
  } = useForm({
    resolver: yupResolver(passwordValidationSchema)
  })

  const onSubmit = async data => {
    try {
      await pb
        .collection("user")
        .confirmPasswordReset(
          token ?? "",
          data.newPassword,
          data.newPasswordConfirm
        )
      reset()
      document.getElementById("sign-in-modal")?.click()
    } catch (error) {
      if (error instanceof Error) {
        toast.error(
          "There was a problem. Please try reset your password again",
          {
            position: "bottom-left",
            autoClose: 5000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "colored"
          }
        )
      }
    }
  }

  return (
    <PageWrapper>
      <Background>
        <div className="h-screen w-screen flex items-center flex-col">
          <PageHeader title={"Enter Your New Password"} subtitle={<></>} />
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="w-full max-w-xl px-4"
          >
            <div className="relative mt-6">
              <input
                type="password"
                className="py-3 px-4 block w-full bg-base-200 text-base-content border-primary/40 rounded-lg text-sm focus:border-secondary focus:ring-secondary disabled:opacity-50 disabled:pointer-events-none "
                placeholder="New password…"
                aria-label="New password…"
                autoComplete="on"
                {...register("newPassword")}
              />
              <div className="text-start text-sm italic text-error-content">
                {errors.newPassword?.message}&nbsp;
              </div>
            </div>
            <div className="relative mt-6">
              <input
                type="password"
                className="py-3 px-4 block w-full bg-base-200 text-base-content border-primary/40 rounded-lg text-sm focus:border-secondary focus:ring-secondary disabled:opacity-50 disabled:pointer-events-none "
                placeholder="Confirm new password…"
                aria-label="Confirm new password…"
                autoComplete="on"
                {...register("newPasswordConfirm")}
              />
              <div className="text-start text-sm italic text-error-content">
                {errors.newPasswordConfirm?.message}&nbsp;
              </div>
            </div>
            <div className="flex flex-row w-full justify-between">
              <button
                disabled={isSubmitting}
                type="submit"
                className={isSubmitting ? "btn btn-gray" : "btn btn-primary"}
              >
                Reset Password
                {isSubmitting && <div className="loading"></div>}
              </button>
            </div>
          </form>
        </div>
      </Background>
    </PageWrapper>
  )
}
