"use client";

import React, { useState } from "react";
import { Button } from "../button";
import { EmailInputBlockProps } from "./types";

const LogoCream = ({ fill = "#FFFEEF" }: { fill?: string }) => {
   const clipPathId = `logo-cream-clip-${React.useId()}`;
   return (
     <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" fill="none" viewBox="0 0 100 99" preserveAspectRatio="xMidYMid meet">
       <g fill={fill} clipPath={`url(#${clipPathId})`}>
         <path d="M23.877 73.439c2.829 9.044 7.288 13.706 25.03 18.07 16.735 4.111 43.31 12.356 48.798 3.65 3.454-5.095 1.534-12.395.415-18.244-.875-3.853-1.756-7.3-2.534-11.074-.255-1.237-2.034-1.22-2.278.022-1.284 6.552-3.528 11.26-8.55 14.482-8.572 6.125-28.7 2.295-39.453-2.272-11.487-4.656-14.696-13.509-15.486-23.126-.296-5.157.437-10.123 1.818-14.392.409-1.254-1.273-2.097-2.045-1.023-6.113 8.464-8.073 23.88-5.71 33.913" opacity=".45" />
         <path d="M74.18 75.362c9.135-2.8 13.845-7.215 18.253-24.779 4.153-16.569 12.481-42.878 3.687-48.31-5.147-3.42-12.52-1.52-18.429-.411-3.89.866-7.373 1.738-11.185 2.508-1.25.253-1.233 2.014.023 2.255 6.618 1.271 11.373 3.493 14.628 8.465 6.186 8.486 2.318 28.412-2.295 39.059-4.704 11.371-13.646 14.549-23.36 15.33-5.21.293-10.226-.432-14.537-1.799-1.267-.405-2.12 1.26-1.034 2.025 8.55 6.051 24.12 7.992 34.255 5.652" opacity=".45" />
         <path d="M76.124 25.562c-2.83-9.044-7.289-13.706-25.03-18.07C34.358 3.38 7.783-4.865 2.3 3.842-1.153 8.937.767 16.237 1.886 22.086c.875 3.852 1.756 7.3 2.534 11.074.256 1.237 2.034 1.22 2.278-.023 1.284-6.552 3.528-11.26 8.55-14.482 8.572-6.124 28.7-2.294 39.453 2.272 11.487 4.657 14.696 13.51 15.486 23.126.296 5.158-.437 10.124-1.818 14.392-.409 1.255 1.273 2.098 2.045 1.024 6.113-8.464 8.073-23.88 5.71-33.913" opacity=".45" />
         <path d="M25.82 23.638c-9.135 2.8-13.845 7.216-18.253 24.78-4.153 16.568-12.48 42.877-3.687 48.31 5.147 3.42 12.52 1.519 18.429.41 3.891-.865 7.374-1.737 11.186-2.508 1.25-.253 1.232-2.013-.023-2.255-6.619-1.27-11.373-3.492-14.629-8.464-6.186-8.487-2.317-28.413 2.296-39.059 4.703-11.372 13.645-14.55 23.36-15.331 5.209-.293 10.225.433 14.537 1.8 1.266.404 2.118-1.26 1.033-2.025-8.55-6.052-24.12-7.992-34.255-5.652" opacity=".45" />
       </g>
       <defs>
         <clipPath id={clipPathId}>
           <path fill="#fff" d="M0 0h100v99H0z" />
         </clipPath>
       </defs>
     </svg>
   );
 };

export const EmailInputBlock: React.FC<EmailInputBlockProps> = props => {
  const {
    anchorId = "email-input",
    title,
    subTitle,
    emailInputDescription,
    inputPlaceholder = "Enter your email here",
    ctaButtonText,
    ctaText,
    caption,
    backgroundColor = "white",
    successFeedback,
    onSubmit,
    themeColor,
    showPinWheel = true,
    padding = "large",
    requiredErrorMessage = "Email is required",
    validationErrorMessage = "Invalid email address",
  } = props || {};

  const buttonLabel = ctaButtonText || ctaText || "Sign me up";

  const backgroundColorClasses: Record<string, string> = {
    green: "bg-bg-fill-brand",
    white: "bg-bg",
    gray90: "bg-[var(--color-text-secondary)]",
  };

  const themeColorClasses: Record<string, string> = {
    green: "bg-bg-fill-brand",
    blue: "bg-bg-fill-brand-supporting",
    orange: "bg-orange-500",
    purple: "bg-bg-fill-brand-tertiary",
    white: "bg-bg",
  };

  const normalizedBg =
    ((backgroundColor as string) || "").trim().toLowerCase() || "white";
  const outerBgClass = backgroundColorClasses[normalizedBg as keyof typeof backgroundColorClasses] || backgroundColorClasses.white;
  const captionTextColorClass = normalizedBg === "white" ? "text-text" : "text-white";

  const normalizedTheme =
   ((themeColor as string) || "").trim().toLowerCase() || "green";
  const containerBgClass = themeColorClasses[normalizedTheme as keyof typeof themeColorClasses] || themeColorClasses.green;

  const darkThemeColors = ["green", "blue", "purple"];
  const isDarkTheme = darkThemeColors.includes(normalizedTheme);
  const textColor = isDarkTheme ? "text-white" : "text-text";
  const errorTextColor = isDarkTheme ? "text-text-inverse" : "text-text";
  const pinwheelFill = normalizedTheme === "white" ? "#E0E0E0" : "#FFFEEF";

  const paddingClass = padding === "none" ? "!py-0 md:!py-0" : "!py-8 md:!py-20";

  const [email, setEmail] = useState("");
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [emailError, setEmailError] = useState("");

  const validateEmail = (email: string) => {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  };

  const handleOnSubmit = () => {
    if (!email.trim()) {
      setEmailError(requiredErrorMessage);
    } else if (!validateEmail(email)) {
      setEmailError(validationErrorMessage);
    } else {
      onSubmit({ email });
      setEmail("");
      setFormSubmitted(true);
      setEmailError("");
    }
  };

  return (
    <section id={anchorId} className={`w-full px-4 ${paddingClass} md:px-0 ${outerBgClass}`}>
      <div
        className={`mx-auto max-w-[1200px] overflow-hidden !rounded-[20px] md:rounded-[20px] flex flex-col items-start !px-5 !pt-6 !pb-10 md:!p-10 md:!pt-12 !h-[344px] md:!w-auto md:!h-[367px] relative ${containerBgClass}`}
      >
        {showPinWheel && (
          <div className="absolute right-[-50px] top-[-30px] hidden h-[420px] w-[420px] pointer-events-none lg:block" aria-hidden="true">
            <LogoCream fill={pinwheelFill} />
          </div>
        )}
        <div className="w-full">
          <div className="lg:w-[548px]">
            {title && (
              <h1 className={`mb-3 text-[2.25rem] leading-[2.5rem] font-black md:text-heading1 md:font-black ${textColor}`}>{title}</h1>
            )}
            {subTitle && (
              <h2 className={`mb-3 text-heading1 font-black ${textColor}`}>
                {subTitle}
              </h2>
            )}

            {emailInputDescription && (
              <p className={`!mb-4 md:!mb-16 text-xl leading-7 font-medium md:text-subheading1 md:!leading-8 md:!font-bold opacity-95 ${textColor}`}>
                {emailInputDescription}
              </p>
            )}
          </div>

          <div className="relative max-w-[548px] flex w-full flex-col items-center sm:flex-row sm:overflow-hidden sm:rounded-3xl sm:border-2 sm:!border-gray-600 sm:bg-white sm:p-1.5 sm:shadow-xl sm:transition-all md:!h-[75px] md:p-2">
            <div className="w-full !rounded-lg border border-transparent bg-white p-1.5 shadow-md sm:border-0 sm:p-0 sm:rounded-none sm:shadow-none">
              <input
                type="email"
                placeholder={inputPlaceholder}
                value={email}
                onChange={e => {
                  const value = e.target.value;
                  setEmail(value);
                  if (formSubmitted) setFormSubmitted(false);
                  if (!value.trim()) {
                    setEmailError(requiredErrorMessage);
                  } else if (!validateEmail(value)) {
                    setEmailError(validationErrorMessage);
                  } else {
                    setEmailError("");
                  }
                }}
                className="w-full flex-grow bg-transparent !pl-4 pr-6 py-3 text-[1rem] leading-none md:text-base font-normal text-text outline-none placeholder:input-text-placeholder md:py-4"
              />
            </div>
            <Button
              buttonLabel={buttonLabel}
              buttonVariant="primary_inverse"
              buttonClassName="capitalize-first whitespace-nowrap rounded-2xl px-8 !text-lg mt-3 w-full sm:mt-0 sm:w-auto sm:absolute sm:right-[8px] sm:top-[calc(50%-28px)]"
              onClick={handleOnSubmit}
            />
          </div>
          {emailError && (
            <p className={`mt-2 text-label4 font-semibold ${errorTextColor}`}>
              {emailError}
            </p>
          )}
          {successFeedback && formSubmitted && !emailError && (
            <p className={`mt-2 text-label4 font-semibold ${textColor}`}>
              {successFeedback}
            </p>
          )}
        </div>
      </div>
      {caption && (
        <div className={`mx-auto max-w-[1200px] px-6 md:px-8 ${captionTextColorClass}`}>{caption}</div>
      )}
    </section>
  );
};

export default EmailInputBlock;