"use client";

import React, { useCallback, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { ConfirmationResult } from "@firebase/auth";
import { LoadingCard } from "@/components/loading";
import { SignUpViews } from "../types";

const SignUpForm = dynamic(() => import("./components/sign-up-form"), {
  loading: () => <LoadingCard />,
});
const OtpVerify = dynamic(() => import("./components/confirmation"), {
  loading: () => <LoadingCard />,
});
const AuthComplete = dynamic(() => import("./components/complete"), {
  loading: () => <LoadingCard />,
});

const SignUp = () => {
  const [currentView, setCurrentView] = useState<SignUpViews>("SIGNUP");
  const [confirmationResult, setConfirmationResult] = useState<
    ConfirmationResult | { confirm: (otp: string) => Promise<any>; verifyId?: string } | undefined
  >();
  const [currentCredential, setCredential] = useState<string | undefined>();
  const handleChangeView = useCallback((view: SignUpViews) => setCurrentView(view), []);
  const [idToken, setIdToken] = useState<string | undefined>();
  const verifyMetaRef = useRef<{ verifyId?: string; verifyCode?: string }>({});
  const [verifyMeta, setVerifyMeta] = useState<{ verifyId?: string; verifyCode?: string }>({});

  const renderView = () => {
    switch (currentView) {
      case "SIGNUP":
        return (
          <SignUpForm
            onChangeView={handleChangeView}
            onSuccess={({ credential, callback }) => {
              setCredential(credential);
              setConfirmationResult(callback as any);
            }}
          />
        );
      case "VERIFY":
        return (
          <OtpVerify
            confirmationResult={confirmationResult as any}
            credential={currentCredential}
            onChangeView={handleChangeView}
            onSuccess={(value, meta) => {
              setIdToken(value);
              const nextMeta = meta || {};
              verifyMetaRef.current = nextMeta;
              setVerifyMeta(nextMeta);
            }}
          />
        );
      case "COMPLETE":
        return (
          <AuthComplete
            idToken={idToken}
            credential={currentCredential}
            verifyId={verifyMeta.verifyId || verifyMetaRef.current.verifyId}
            verifyCode={verifyMeta.verifyCode || verifyMetaRef.current.verifyCode}
          />
        );

      default:
        return (
          <SignUpForm
            onChangeView={handleChangeView}
            onSuccess={({ credential, callback }) => {
              setCredential(credential);
              setConfirmationResult(callback as any);
            }}
          />
        );
    }
  };
  return renderView();
};

export default SignUp;
