import { Stepper } from "@/components/ui/stepper";
import { useAuth } from "@/store/auth";
import { useVerify } from "@/store/verify";
import { Eye, MailCheck, ScanFace } from "lucide-react";
import { useEffect, type FC } from "react";
import { Navigate, Outlet, useLocation, useNavigate } from "react-router";

const steps = [
  {
    id: "email",
    icon: <MailCheck size={18} />,
    label: "Verify Email",
    description: "Confirm your address",
  },
  {
    id: "avatar",
    icon: <ScanFace size={20} />,
    label: "Profile Picture",
    description: "Add profile image",
  },
  {
    id: "review",
    icon: <Eye size={20} />,
    label: "Done",
    description: "Review & Quit",
  },
];

const VerificationLayout: FC = () => {
  const location = useLocation();
  const profile = useAuth((s) => s.profile);

  const step = useVerify((s) => s.step);
  const loadStep = useVerify((s) => s.loadStep);

  const redirect = useVerify((s) => s.redirect);
  const setRedirect = useVerify((s) => s.setRedirect);

  const navigate = useNavigate();

  useEffect(() => {
    if (profile) loadStep(profile);
  }, [loadStep, profile]);

  useEffect(() => {
    if (location.state?.from) {
      setRedirect(location.state.from);
    }
  }, [location.state?.from, setRedirect]);

  useEffect(() => {
    if (step === false) {
      navigate(redirect ?? "/", { state: { reset: true } });
    }
  }, [navigate, redirect, step]);

  if (
    step === "email" &&
    !location.pathname.startsWith("/verify/email") &&
    location.pathname.replace(/\/$/i, "") !== "/verify"
  ) {
    return <Navigate to="/verify/email" />;
  }

  if (step === "avatar" && !location.pathname.startsWith("/verify/avatar")) {
    return <Navigate to="/verify/avatar" />;
  }

  if (step === "review" && !location.pathname.startsWith("/verify/review")) {
    return <Navigate to="/verify/review" />;
  }

  return (
    <div className="w-full h-screen max-h-screen overflow-y-auto flex flex-col items-center sm:justify-center bg-white/50 dark:bg-black/50">
      <div className="w-full h-full sm:w-auto sm:h-auto">
        {location.pathname.replace(/\/$/i, "") !== "/verify" &&
          typeof step === "string" && (
            <Stepper steps={steps} currentStep={step} />
          )}
        <Outlet />
      </div>
    </div>
  );
};

export default VerificationLayout;
