"use client"

import React, { useEffect } from "react";
import { toast } from "react-toastify";
import PocketBase from 'pocketbase';
import PageWrapper from "@/components/Utilities/PageWrapper";
import { usePathname, useRouter } from 'next/navigation';
import Background from "@/components/Utilities/Background";
import PageHeader from "@/sections/PageHeader";

const pb = new PocketBase(process.env.NEXT_PUBLIC_POCKETBASE_URL as string);

export default function ConfirmVerification() {
  const pathName = usePathname();
  const router = useRouter();
  const token = pathName.split('/').at(-1);

  useEffect(() => {
    (async () => {
        try {
            await pb.collection('user').confirmVerification(
              token ?? ""
            );
          } catch (error) {
            if (error instanceof Error) {
              toast.error("There was a problem. Please try confirm your email again", {
                position: "bottom-left",
                autoClose: 5000,
                hideProgressBar: false,
                closeOnClick: true,
                pauseOnHover: true,
                draggable: true,
                progress: undefined,
                theme: "colored",
              });
            }
          }
    })()
  }, [])

  const handleSignInRedirect = () => {
    document.getElementById("sign-in-modal")?.click();
  };

  return (
    <PageWrapper>
        <Background>
        <div className="h-screen w-screen flex items-center flex-col">
        <PageHeader
          title={"Your Email Was Verified"}
          subtitle={<></>}
        />
        <button onClick={handleSignInRedirect} className="btn btn-primary mt-4">
          Go to Sign In
        </button>
      </div>
      </Background>
    </PageWrapper>
  );
}
