"use client";
import React, { useEffect, useState } from "react";
import axiosInstance from "./axiosInstance";
import { PhoneInput } from "react-international-phone";
import { useCountry } from "@/context/CountryContext";
export default function Form({ looking_for, modalData }) {
  const defaultCountry = useCountry();
  const [currentUrl, setCurrentUrl] = useState("");
  const [full_name, setName] = useState("");
  const [email_address, setEmail] = useState("");
  const [phone_number, setPhone] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  useEffect(() => {
    setCurrentUrl(window.location.href);
  }, []);
  const validatePhoneNumber = (number) => {
    // Adjust this regex based on the phone number format you expect
    const phoneRegex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
    return phoneRegex.test(number);
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    setName("");
    setEmail("");
    setPhone("");
    setErrorMessage("");

    if (!validatePhoneNumber(phone_number)) {
      setErrorMessage("Please enter a valid phone number with country code.");
      return;
    }
    // Normalize data fields
    const normalizeField = (field) =>
      field && typeof field === "object" ? Object.values(field)[0] : field;
    const data = {
      full_name: normalizeField(full_name),
      email_address: normalizeField(email_address),
      phone_number: normalizeField(phone_number),
      page_url: normalizeField(currentUrl),
      source: normalizeField("bahriatown-dubai.com"),
      looking_for: normalizeField(looking_for),
      stage: "New Lead",
      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 {
      const response = await axiosInstance.post(
        `https://api.salwaproperties.com/types`,
        data
      );
      window.location.href = "/thank-you";
    } catch (error) {
      if (error.response) {
        setErrorMessage(`Error: ${error.response.data.message}`);
      } else if (error.request) {
        setErrorMessage("No response from the server. Please try again later.");
      } else {
        setErrorMessage(
          "An error occurred while submitting the form. Please try again."
        );
      }
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <div className="mb-3">
        <div className="form-group">
          <input
            type="text"
            className="form-control"
            placeholder="Name"
            id="name"
            name="name"
            value={full_name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>
      </div>
      <div className="mb-3">
        <div className="form-group">
          <input
            type="email"
            className="form-control"
            placeholder="Email Address"
            id="email"
            name="email"
            value={email_address}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
      </div>
      <div className="mb-3">
        <div className="form-group">
          {defaultCountry ? (
            <PhoneInput
              value={phone_number}
              defaultCountry={defaultCountry}
              onChange={setPhone}
              forceDialCode
              placeholder="Phone Number"
              className="form-control d-flex"
              required
            />
          ) : null}
        </div>
      </div>
      <div className="d-flex justify-content-center">
        <button className="webbutton" type="submit">
          Book Now
        </button>
      </div>
      {errorMessage && <p className="text-danger">{errorMessage}</p>}
    </form>
  );
}
