"use client";

import { Controller, useForm } from "react-hook-form";
import Link from "next/link";
import dynamic from "next/dynamic";
import { FaChevronLeft, FaTableList } from "react-icons/fa6";
import { FaCheckCircle, FaChevronRight } from "react-icons/fa";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Turnstile, TurnstileInstance } from "@marsidev/react-turnstile";
import { useFormState, useFormStatus } from "react-dom";

import { SUPPORT_EMAIL } from "@/constants/signup-form-constants";
import TextInput from "@/components/common/text-input";
import { AUTOCOMPLETE_VALUES } from "@/constants/signup-auto-complete-mapping";
import Select from "@/components/common/select";
import TextArea from "@/components/common/textarea";
import Button from "@/components/common/button";
import PFRSamLogo from "@/components/common/sprites/pfr-sam-logo-sprite";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { CONTACTS_MAPPING } from "@/constants/ui-helpers";
import Alert from "@/components/common/alert";
import { sendEmailSupport } from "@/services/participant/contact-us/contact-us-actions";
import FormError from "@/components/common/form-error";

type ContactUsSchema = {
  firstName: string;
  lastName: string;
  email: string;
  typeOfEnquiry: number;
  message: string;
};

type ContactUsProps = {
  firstName?: string;
  lastName?: string;
  email?: string;
};

const DynamicMapComponent = dynamic(
  () =>
    import("@/components/pages/participant/contact-us/partials/map-component"),
  { ssr: false }
);

function SubmitButton({ isTurnstileReady }: { isTurnstileReady: boolean }) {
  const { pending } = useFormStatus();

  const getButtonLabel = () => {
    if (pending) return "Sending your enquiry...";
    if (!isTurnstileReady) return "Waiting for security verification...";
    return "Submit enquiry";
  };

  return (
    <Button
      fullWidth
      aria-disabled={pending || !isTurnstileReady}
      btnLabel={getButtonLabel()}
      customVariant="black"
      endContent={pending || !isTurnstileReady ? null : <FaChevronRight />}
      isDisabled={pending || !isTurnstileReady}
      isLoading={pending}
      type="submit"
    />
  );
}

function ContactUs({ firstName, lastName, email }: ContactUsProps) {
  const turnstileSiteKey = process.env
    .NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY as string;
  const turnstileRef = useRef<TurnstileInstance>(null);
  const isTurnstileReady = !!turnstileRef.current?.getResponse();
  const [token, setToken] = useState<string>();
  const router = useRouter();
  const [isSuccess, setIsSuccess] = useState(false);

  const { control, watch } = useForm<ContactUsSchema>({
    defaultValues: {
      firstName: firstName || "",
      lastName: lastName || "",
      email: email || "",
      typeOfEnquiry: undefined,
      message: "",
    },
    mode: "all",
  });

  const textArea = watch("message");
  const countChars = textArea ? textArea.length : 0;

  const [state, formAction] = useFormState(sendEmailSupport.bind(null, token), {
    success: false,
    error: "",
  });

  const handleClickJoinCommunity = () => {
    router.push(INTERNAL_PAGES.participant.signup.main);
  };

  const handleClickOpportunities = () => {
    router.push(INTERNAL_PAGES.participant.opportunities.main);
  };

  const handleClickHome = () => {
    router.push(INTERNAL_PAGES.participant.homepage);
  };

  useEffect(() => {
    if (!state.success) {
      turnstileRef.current?.reset();
    }

    if (state.success) {
      setIsSuccess(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      setIsSuccess(false);
    }
  }, [state, router]);

  return (
    <div className="bg-participant-light dark:bg-participant-dark min-h-screen flex flex-col lg:flex-row py-12">
      <div className="lg:order-1 order-2 top-0 m-5 z-0 flex flex-col">
        <DynamicMapComponent />
        <div className="mt-8">
          <span className="font-inter font-black text-2xl text-black dark:text-white tracking-tight">
            How to get in touch with us
          </span>
          {CONTACTS_MAPPING.map((contact, index) => {
            let baseStyles;
            const Icon = contact.icon;

            if (contact.name === "Email") {
              baseStyles =
                "flex flex-row space-x-4 items-center py-2 font-noto underline decoration-dotted underline-offset-4 cursor-pointer";
              return (
                <Link
                  key={index}
                  className={baseStyles}
                  href={`mailto:${contact.value}`}
                >
                  <Icon />
                  <p>{contact.value}</p>
                </Link>
              );
            } else {
              baseStyles =
                "flex flex-row space-x-4 items-center py-2 font-noto";
              return (
                <div key={index} className={baseStyles}>
                  <Icon />
                  <p>{contact.value}</p>
                </div>
              );
            }
          })}
        </div>
      </div>

      <div className="lg:order-2 order-1 flex-1 p-8 space-y-8 bg-white m-5 xl:me-12 rounded-xl light">
        <h1 className="font-inter font-black text-2xl xl:text-5xl text-black">
          {isSuccess
            ? "Thank you! Your enquiry has been sent to our team."
            : firstName
            ? `${firstName}, we would love to hear from you.`
            : "We would love to hear from you."}
        </h1>
        {isSuccess && (
          <>
            <div className="flex flex-col text-center items-center justify-center space-y-12">
              <FaCheckCircle className="text-green-500 size-16" />
              <p className="font-noto text-base text-black">
                Thank you for getting in touch! We will get back to you as soon
                as possible. In the meantime, you can check our current paid
                studies or find out more about us and what we do.
              </p>
              <p className="font-noto text-base text-black">
                If you are not part of our community yet, we would love for you
                to join us!
              </p>
            </div>
            <div className="flex flex-col space-y-4 items-center justify-center">
              <Button
                fullWidth
                btnLabel="Join our community"
                customVariant="primary"
                startContent={<PFRSamLogo width={15} />}
                onClick={handleClickJoinCommunity}
              />
              <Button
                fullWidth
                btnLabel="Current opportunities"
                customVariant="secondary"
                startContent={<FaTableList className="size-3" />}
                onClick={handleClickOpportunities}
              />
              <Button
                fullWidth
                btnLabel="Back to participant homepage"
                startContent={<FaChevronLeft className="size-3" />}
                variant="ghost"
                onClick={handleClickHome}
              />
            </div>
          </>
        )}
        {!isSuccess && (
          <>
            <p className="font-noto text-base text-black">
              Use the contact form to get in touch or email us directly at{" "}
              <Link
                className="underline underline-offset-2 decoration-dotted cursor-pointer font-bold"
                href={`mailto:${SUPPORT_EMAIL}`}
              >
                our support email
              </Link>
              . We&apos;ll get back to you as soon as possible.
            </p>
            <form
              noValidate
              action={formAction}
              className="flex flex-col gap-4"
            >
              <Controller
                control={control}
                name="firstName"
                render={({ fieldState, field }) => {
                  return (
                    <TextInput
                      isClearable
                      autoComplete={AUTOCOMPLETE_VALUES.GIVEN_NAME}
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      label="First name"
                      name={field.name}
                      placeholder="Your first name"
                    />
                  );
                }}
              />
              {state.errors?.firstName && (
                <FormError text={state.errors.firstName} />
              )}
              <Controller
                control={control}
                name="lastName"
                render={({ fieldState, field }) => {
                  return (
                    <TextInput
                      isClearable
                      autoComplete={AUTOCOMPLETE_VALUES.FAMILY_NAME}
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      label="Last name"
                      name={field.name}
                      placeholder="Your last name"
                    />
                  );
                }}
              />
              {state.errors?.lastName && (
                <FormError text={state.errors.lastName} />
              )}
              <Controller
                control={control}
                name="email"
                render={({ fieldState, field }) => {
                  return (
                    <TextInput
                      isClearable
                      autoComplete={AUTOCOMPLETE_VALUES.EMAIL}
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      label="Email address"
                      name={field.name}
                      placeholder="Your email address"
                    />
                  );
                }}
              />
              {state.errors?.email && <FormError text={state.errors.email} />}
              <Controller
                control={control}
                name="typeOfEnquiry"
                render={({ fieldState, field }) => {
                  return (
                    <Select
                      control={control}
                      data={[
                        { id: 1, title: "Technical issue" },
                        { id: 2, title: "Incentive payment" },
                        { id: 3, title: "Feedback" },
                        { id: 4, title: "General support" },
                      ]}
                      description="Select the option that best represents your enquiry. This will help us to respond as quickly as possible."
                      fieldProps={field}
                      fieldState={fieldState}
                      label="Type of enquiry"
                      name={field.name}
                      placeholder="Select your enquiry type"
                    />
                  );
                }}
              />
              {state.errors?.typeOfEnquiry && (
                <FormError text={state.errors.typeOfEnquiry} />
              )}
              <Controller
                control={control}
                name="message"
                render={({ fieldState, field }) => {
                  return (
                    <TextArea
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      label={`Your message (${countChars}/500 characters)`}
                      maxLength={500}
                      minLength={2}
                      minRows={4}
                      name={field.name}
                      placeholder="Your message here"
                    />
                  );
                }}
              />
              {state.errors?.message && (
                <FormError text={state.errors.message} />
              )}
              <Turnstile
                ref={turnstileRef}
                as="aside"
                options={{
                  action: "contact-us-participant",
                  theme: "light",
                  size: "flexible",
                }}
                siteKey={turnstileSiteKey}
                onSuccess={(token) => setToken(token)}
              />
              {state.error && (
                <Alert
                  message={state.error}
                  title={`Error (${state.errorCode})`}
                  variant="error"
                />
              )}
              {state.errors && (
                <Alert
                  message="Some fields have missing or incorrect information. Please review the highlighted fields and correct any errors."
                  title="Error"
                  variant="alert"
                />
              )}
              <SubmitButton isTurnstileReady={isTurnstileReady} />
            </form>
          </>
        )}
      </div>
    </div>
  );
}

export default ContactUs;
