import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAuth } from "@/store/auth";
import { useVerify } from "@/store/verify";
import maskEmail from "@/util/maskEmail";
import { useCallback, useEffect, useMemo, useState, type FC } from "react";
import { useNavigate } from "react-router";

const VerifyEmailPage: FC = () => {
  const profile = useAuth((s) => s.profile);

  const requestOtp = useVerify((s) => s.requestOTP);
  const requesting = useVerify((s) => s.requesting);
  const requested = useVerify((s) => s.requested);

  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const matches = useMemo(
    () => email === profile?.email,
    [email, profile?.email],
  );

  const handleNext = useCallback(() => {
    if (matches) {
      requestOtp();
    }
  }, [matches, requestOtp]);

  useEffect(() => {
    if (requested) {
      navigate("/verify/email/otp");
    }
  }, [navigate, requested]);

  return (
    <div className="flex flex-col items-stretch gap-2 sm:max-w-sm mx-auto p-4">
      <h1 className="text-xl font-medium dark:text-gray-200">E-Mail Address</h1>
      <p className="text-sm dark:text-gray-400">
        Please fill in your email address used in this account.
      </p>
      <Input
        value={email}
        placeholder={maskEmail(profile?.email ?? "")}
        onChange={(e) => {
          e.preventDefault();
          setEmail(e.target.value);
        }}
      />
      <Button
        className={`mt-3 ${!matches ? "opacity-60" : ""}`}
        onClick={handleNext}
        disabled={!matches || requesting}
        loading={requesting}
      >
        Next
      </Button>
    </div>
  );
};

export default VerifyEmailPage;
