"use client";

import { FiMail } from "react-icons/fi";
import z from "zod";
import Input from "../../ui/CustomInput";
import Button from "../../ui/Button";
import { useModal } from "../../../lib/modal-system/ModalContext";
import { useAppForm } from "../../../hooks/useAppForm";
import useResendEmail from "../../../hooks/features/auth/resend-email/useResendEmail";

const schema = z.object({
  email: z
    .string()
    .trim()
    .min(1, "Please enter your email address")
    .email("Please enter a valid email address (e.g. john@example.com)")
    .refine((email) => {
      const [, domain] = email.split("@");

      if (!domain) return false;

      const labels = domain.split(".");

      return labels.every(
        (label) =>
          label.length > 0 && !label.startsWith("-") && !label.endsWith("-"),
      );
    }, "Please enter a valid email address (e.g. john@example.com)"),
});
type Schema = z.infer<typeof schema>;

export default function EnterMailForResendLink() {
  const { openModal } = useModal();
  const { handleResendEmail, loading } = useResendEmail();

  const { register, reset, errors, handleSubmit } = useAppForm<Schema>({
    schema,
    defaultValues: { email: "" },
    onSubmit: async (data) => {
      try {
        await handleResendEmail({ email: data.email });
        reset();
        openModal("CHECK_EMAIL_FOR_VERIFICATION", { email: data.email });
      } catch {
        // error is already toasted by the hook
      }
    },
  });

  return (
    <>
      {/* Icon */}
      <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-[#E5D8FF] text-link-1 md:h-16 md:w-16">
        <FiMail size={24} />
      </div>

      {/* Heading */}
      <h2 className="mt-7 text-center font-heading text-xl font-semibold text-heading">
        Resend Verification Email
      </h2>

      {/* Description */}
      <p className="mx-auto mt-4 max-w-[320px] text-center font-body text-base leading-7 text-text">
        Enter the email address linked to your account and we'll send you a new
        verification link.
      </p>

      {/* Email field */}
      <div className="mt-6">
        <label className="mb-2 block font-body text-sm font-medium text-heading">
          Email<span className="text-danger">*</span>
        </label>

        <Input
          register={register("email")}
          error={errors.email?.message}
          icon={<FiMail />}
          placeholder="Enter your email address"
        />
      </div>

      {/* Submit */}
      <Button disabled={loading} className="mt-6 w-full" onClick={handleSubmit}>
        {loading ? "Sending..." : "Send Verification Link"}
      </Button>

      {/* Back to Login */}
      <div className="mt-6 text-center">
        <button
          type="button"
          onClick={() => openModal("LOGIN", {})}
          className="cursor-pointer font-body text-sm font-medium text-link-1"
        >
          Back to Login
        </button>
      </div>
    </>
  );
}
