"use client";

import Button from "../ui/Button";
import Input from "../ui/CustomInput";
import CustomPhoneInput from "../ui/CustomPhoneInput";
import { useModal } from "../../lib/modal-system/ModalContext";
import Link from "next/link";
import { useAppForm } from "../../hooks/useAppForm";
import {
  ContactFormValues,
  contactSchema,
} from "../../hooks/features/contact/schema";
import useContactUs from "../../hooks/features/contact/useContactUs";
import { AxiosError } from "axios";
import { formatStringWithUppercase } from "../../utils/helper";
import CustomLink from "../ui/CustomLink";

export default function ContactUsModal() {
  const { closeModal } = useModal();

  const { contactToSupport, isContactingSupport } = useContactUs();

  const { control, register, handleSubmit, errors, reset, setError } =
    useAppForm<ContactFormValues>({
      defaultValues: {
        firstName: "",
        lastName: "",
        email: "",
        mobileNumber: {
          dialCode: "",
          number: "",
        },
        query: "",
      },
      schema: contactSchema,
      onSubmit: async (data) => {
        try {
          await contactToSupport(data);
          closeModal();

          reset();
        } catch (error) {
          const axiosError = error as AxiosError<{
            message?: string;
            errors?: Record<string, string[]>;
          }>;

          const fieldErrors = axiosError?.response?.data?.errors;

          if (fieldErrors) {
            Object.entries(fieldErrors).forEach(([field, messages]) => {
              setError(field as keyof ContactFormValues, {
                type: "server",
                message: formatStringWithUppercase(messages[0]),
              });
            });
          }
        } finally {
        }
      },
    });

  return (
    <div className="relative">
      {/* Header */}
      <div className="mb-8 text-center">
        <h2 className="font-heading text-lg xl:text-xl 2xl:text-2xl font-semibold text-heading">
          Get in Touch
        </h2>

        <p className="mx-auto mt-3 max-w-130 text-base text-text">
          Have questions about our AI image detection, need support? Fill out
          the form, and well get back to you soon.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-3 2xl:space-y-5">
        {/* First Name / Last Name */}
        <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
          <Input
            label="First Name"
            placeholder="Enter Your First Name"
            register={register("firstName")}
            error={errors.firstName?.message}
          />

          <Input
            label="Last Name"
            placeholder="Enter Your Last Name"
            register={register("lastName")}
            error={errors.lastName?.message}
          />
        </div>

        <div className="mt-3">
          <Input
            type="email"
            label="Email"
            placeholder="Enter Your Email"
            register={register("email")}
            error={errors.email?.message}
          />
        </div>

        <div className="mt-3">
          <CustomPhoneInput
            label="Phone Number"
            name="mobileNumber"
            control={control}
            error={errors?.mobileNumber?.number?.message}
            placeholder="Enter Your Phone Number"
          />
        </div>

        {/* Message */}
        <div>
          <label className="mb-1 block text-sm font-medium text-heading">
            Message
          </label>

          <textarea
            rows={3}
            placeholder="Enter Your Message"
            {...register("query")}
            className="
              w-full
              rounded-xl
              border
              border-[#E5DFFF]
              bg-white
              px-4
              py-3
              text-base
              text-heading
              outline-none
              transition-all
              placeholder:text-gray-400
              focus:border-[#8B5CF6]
              focus:ring-2
              align-middle
              focus:ring-[#8B5CF6]/10
            "
          />
          {errors.query?.message && (
            <p className="mt-1 text-xs text-danger">{errors.query.message}</p>
          )}
        </div>

        {/* Submit */}
        <Button
          type="submit"
          className="w-full"
          BtnInnerclassName="!justify-center !py-4"
          loading={isContactingSupport}
        >
          Send Message
        </Button>

        {/* Footer */}
        <p className="text-center text-sm text-text ">
          By submitting this form, you agree to our{" "}
          <CustomLink
            href="/terms-and-conditions"
            onClick={() => closeModal()}
            className="cursor-pointer text-link"
          >
            Terms and Conditions
          </CustomLink>{" "}
          and{" "}
          <CustomLink
            href="/privacy-policy"
            onClick={() => closeModal()}
            className="cursor-pointer text-link"
          >
            Privacy Policy
          </CustomLink>
          .
        </p>
      </form>
    </div>
  );
}
