"use client";

import { TextInput } from "@/components/ui/TextInput/TextInput";
import {
  BottomActionButton,
  BottomActionButtonProps,
} from "@/components/widgets/BottomActionButton/BottomActionButton";
import { useDynamicSize } from "@/hooks/DOM/useDynamicSize";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useEffect, useState } from "react";
import PrivacyTermsConsent from "@/components/widgets/PrivacyTermsConsent/PrivacyTermsConsent";
import PrivacySecurityBanner from "@/components/widgets/PrivacySecurityBanner/PrivacySecurityBanner";

const formSchema = z.object({
  email: z.email({
    message: "Please enter a valid email address",
  }),
});

interface EmailProps extends Omit<React.ComponentProps<"div">, "title"> {
  textInputProps: React.ComponentProps<typeof TextInput>;
  bottomActionButtonProps?: BottomActionButtonProps;
  image?: React.ReactNode;
  privacyTermsConsentProps?: React.ComponentProps<typeof PrivacyTermsConsent>;
  privacySecurityBannerProps?: React.ComponentProps<
    typeof PrivacySecurityBanner
  >;
}

function Email({
  textInputProps,
  bottomActionButtonProps,
  image,
  privacyTermsConsentProps,
  privacySecurityBannerProps,
  ...props
}: EmailProps) {
  const {
    height: bottomActionButtonHeight,
    elementRef: bottomActionButtonRef,
  } = useDynamicSize<HTMLDivElement>({
    defaultHeight: 132,
  });
  const [isTouched, setIsTouched] = useState(false);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: String(textInputProps.value || ""),
    },
  });

  useEffect(() => {
    form.setValue("email", String(textInputProps.value || ""));
  }, [textInputProps.value, form]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    form.setValue("email", value);
    form.trigger("email");
    textInputProps.onChange?.(e);
  };

  const isFormValid = form.formState.isValid && form.getValues("email");

  return (
    <div
      className="w-full flex flex-col items-center gap-[26px]"
      {...props}
      style={{
        paddingBottom: `${bottomActionButtonHeight}px`,
        ...props.style,
      }}
    >
      <TextInput
        label="Email"
        placeholder="Enter your Email"
        type="email"
        {...textInputProps}
        onChange={handleChange}
        onBlur={() => {
          setIsTouched(true);
          form.trigger("email");
        }}
        aria-invalid={isTouched && !!form.formState.errors.email}
        aria-errormessage={
          isTouched ? form.formState.errors.email?.message : undefined
        }
      />
      {image}
      {privacySecurityBannerProps && (
        <PrivacySecurityBanner
          {...privacySecurityBannerProps}
          className={cn(privacySecurityBannerProps.className, "mt-[26px]")}
        />
      )}
      {bottomActionButtonProps && (
        <BottomActionButton
          {...bottomActionButtonProps}
          actionButtonProps={{
            ...bottomActionButtonProps.actionButtonProps,
            disabled: !isFormValid,
          }}
          className={cn(
            "max-w-[560px] z-10",
            bottomActionButtonProps.className
          )}
          ref={bottomActionButtonRef}
          childrenUnderButton={
            privacyTermsConsentProps && (
              <PrivacyTermsConsent
                {...privacyTermsConsentProps}
                className={cn(privacyTermsConsentProps.className, "mt-5")}
              />
            )
          }
        />
      )}
    </div>
  );
}

export { Email };
