"use client";
import { useForm } from "react-hook-form";
import axiosInstance from "./axiosInstance";
import { domain } from "@/app/domain";
import InputField from "@/components/InputField";
import PhoneInputField from "@/components/PhoneInputField";
import { useEffect, useState } from "react";
export default function Form({ looking_for, modalData }) {
  const [currentURL, setCurrentURL] = useState("");
  useEffect(() => {
    setCurrentURL(window.location.href);
  }, []);
  const APIKEY = process.env.NEXT_PUBLIC_API_KEY;
  const {
    register,
    handleSubmit,
    reset,
    control,
    formState: { errors },
  } = useForm();
  const onSubmit = async (data) => {
    reset();
    const normalizeField = (field) =>
      field && typeof field === "object" ? Object.values(field)[0] : field;
    const formData = {
      ...data,
      source: normalizeField(domain),
      looking_for: normalizeField(looking_for),
      stage: "New Lead",
      page_url: modalData?.cardurl || currentURL,
      project_name: normalizeField(modalData?.project_name),
      community_name: normalizeField(modalData?.community_name),
      developer_name: normalizeField(modalData?.developer_name),
      unit_type: normalizeField(modalData?.unit_type),
      bedroom: normalizeField(modalData?.bedroom),
      size: normalizeField(modalData?.size),
      price: normalizeField(modalData?.price),
    };

    try {
      await axiosInstance.post(
        `https://api.uae-offplan.com/api/lead-form`,
        formData,
        {
          headers: {
            Authorization: `Bearer ${APIKEY}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
        }
      );
      window.location.href = "/thank-you";
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <InputField
        label="Name"
        type="text"
        name="full_name"
        placeholder="Name"
        register={register("full_name", { required: "Name is required" })}
        errors={errors}
      />
      <InputField
        label="Email Address"
        type="email"
        name="email_address"
        placeholder="Email Address"
        register={register("email_address", {
          required: "Email is required",
          pattern: {
            value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            message: "Invalid email format",
          },
        })}
        errors={errors}
      />
      <PhoneInputField name="phone_number" control={control} errors={errors} />
      <div className="d-flex justify-content-center">
        <button className="webbutton" type="submit">
          Submit Now
        </button>
      </div>
    </form>
  );
}
