import React, { useEffect, useState } from "react";
import "./Contact_us_Form.css";
import Breadcrumb_comp from "../../common-components/breadcrumb-comp/Breadcrumb_comp";
import { Col, Form, Row } from "react-bootstrap";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { useForm, Controller } from "react-hook-form";
import { FullScreen, useFullScreenHandle } from "react-full-screen";
import classNames from "classnames";
import Success_New from "../../Animation/Success_New/Success_New";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faCircleXmark,
  faEnvelope,
  faMapLocationDot,
  faMaximize,
  faMinimize,
  faPhone,
} from "@fortawesome/free-solid-svg-icons";
import Green_round_btn from "../../common-components/common_btn/green_round_btn/Green_round_btn";
import Success_Modal from "../../common-components/common_modal/success_modal/Success_Modal";
import { useDispatch, useSelector } from "react-redux";
import { contactusForm } from "../../../features/contact_us/contactusSlice";
import { appSetup } from "../../../features/master/masterSlice";
import MapView from "./map";
import Green_btn from "../../common-components/common_btn/green_btn/Green_btn";
import {
  faWhatsapp,
  faWhatsappSquare,
} from "@fortawesome/free-brands-svg-icons";

function Contact_us_Form() {
  const dispatch = useDispatch();

  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const [showMap, setShowMap] = useState(false);
  const handle = useFullScreenHandle();

  const {
    control,
    reset,
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const expandMap = () => {
    if (handle.active) {
      handle.exit();
    } else {
      handle.enter();
    }
  };

  const toggleMap = () => {
    if (!showMap) window.scrollTo({ top: 0, behavior: "smooth" });
    if (showMap && handle.active) {
      handle.exit();
    }
    setShowMap(!showMap);
  };

  const onSubmit = (data) => {
    dispatch(contactusForm(data));
    console.log("Form Submitted", data);
    setShowSucsessModal(true);
    reset();
  };

  const breadcrumbs = [
    { label: "Home", link: "/", isActive: false },
    { label: "CONTACT US", link: "", isActive: true },
  ];

  const app_setup = useSelector((state) => state.master.app_setup);

  useEffect(() => {
    dispatch(appSetup());
  }, [dispatch]);

  const buildWhatsAppHref = (rawNumber, defaultCountryCode = "91") => {
    if (!rawNumber) return null;

    let cleaned = String(rawNumber).replace(/\D/g, "");

    cleaned = cleaned.replace(/^0+/, "");

    if (cleaned.length === 10) {
      cleaned = `${defaultCountryCode}${cleaned}`;
    }

    if (!/^\d+$/.test(cleaned)) return null;
    if (cleaned.length < 11 || cleaned.length > 15) {
      return null;
    }

    const url = `https://wa.me/${cleaned}`;

    return url;
  };

  const phoneHref = buildWhatsAppHref(app_setup?.alt_contact_no);
  return (
    <section className="Contact_us_Form">
      <Breadcrumb_comp breadcrumbs={breadcrumbs} />

      <div className="flipIn">
        <div className="container-fluid">
          <div className="heading_holder text-center">
            <h4 className="heading_text">Contact Us</h4>
          </div>

          <div className="Form_section_holder">
            {!showMap && (
              <Row className="justify-content-center">
                <Col xxl={10} xl={10} lg={10} md={11} sm={12}>
                  <div className="Information-client">
                    <Row className="me-0 ms-0">
                      <Col
                        xxl={7}
                        xl={7}
                        lg={6}
                        md={12}
                        xs={12}
                        sm={12}
                        className="pe-xl-0 pe-xxl-0 pe-lg-0 pe-md-0 p-0"
                      >
                        <div className="form_holder">
                          <div className="leftdivv">
                            {!showSuccessModal ? (
                              <>
                                <Form>
                                  <Form.Group className="mb-4">
                                    <Form.Control
                                      type="text"
                                      placeholder="Your Name"
                                      {...register("name", {
                                        required: "Name is required",
                                      })}
                                      className={classNames("", {
                                        "is-invalid": errors?.name,
                                      })}
                                      onKeyDown={(event) => {
                                        if (!/[A-Za-z ]/.test(event.key)) {
                                          event.preventDefault();
                                        }
                                      }}
                                    />
                                    {errors.name && (
                                      <div className="invalid-feedback">
                                        {errors.name.message}
                                      </div>
                                    )}
                                  </Form.Group>

                                  <Form.Group className="mb-4">
                                    <Form.Control
                                      type="email"
                                      placeholder="E-mail Address"
                                      {...register("email", {
                                        required: "Email Id required",
                                        pattern: {
                                          value:
                                            /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
                                          message: "Email Id Invalid",
                                        },
                                      })}
                                      className={classNames("", {
                                        "is-invalid": errors?.email,
                                      })}
                                    />
                                    {errors.email && (
                                      <div className="invalid-feedback">
                                        {errors.email.message}
                                      </div>
                                    )}
                                  </Form.Group>
                                  <Form.Group className="mb-4">
                                    <Controller
                                      name="number"
                                      control={control}
                                      defaultValue=""
                                      rules={{
                                        required: "Mobile number is required",
                                        pattern: {
                                          value:
                                            /^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{4})[-. )]*(\d{4})[-. ]*(\d{4})(?: *x(\d+))?\s*$/,
                                          message: "Number must be 10 digit",
                                        },
                                      }}
                                      render={({
                                        field: { onChange, value },
                                      }) => (
                                        <PhoneInput
                                          country={"in"}
                                          value={value}
                                          placeholder="Enter Mobile Number"
                                          onChange={onChange}
                                          className={classNames("mb", {
                                            "is-invalid": errors?.number,
                                          })}
                                          inputProps={{
                                            name: "number",
                                            required: true,
                                            autoFocus: true,
                                          }}
                                        />
                                      )}
                                    />
                                    {errors.number && (
                                      <div className="invalid-feedback d-block">
                                        {errors.number.message}
                                      </div>
                                    )}
                                  </Form.Group>
                                  <Form.Group className="mb-4">
                                    <Form.Control
                                      as="textarea"
                                      {...register("message", {
                                        required: "Message required",
                                      })}
                                      className={classNames("", {
                                        "is-invalid": errors?.message,
                                      })}
                                      rows={4}
                                      placeholder="Your Message"
                                    />
                                    {errors.message && (
                                      <div className="invalid-feedback">
                                        {errors.message.message}
                                      </div>
                                    )}
                                  </Form.Group>
                                </Form>

                                <div className="btndiv">
                                  <Green_btn
                                    btnText={"Submit"}
                                    onClick={handleSubmit(onSubmit)}
                                  />
                                </div>
                              </>
                            ) : (
                              <>
                                <Success_Modal
                                  show={showSuccessModal}
                                  onHide={() => {
                                    setShowSucsessModal(false);
                                  }}
                                  successText="Message Sent Successfully!"
                                />
                              </>
                            )}
                          </div>
                        </div>
                      </Col>

                      <Col
                        xxl={5}
                        xl={5}
                        lg={6}
                        md={12}
                        sm={12}
                        xs={12}
                        className="ps-xxl-0 ps-xl-0 ps-lg-0 ps-md-0 p-0"
                      >
                        <div className="leftdivv1">
                          <div className="d-flex align-items-center information my-4">
                            <div className="fonticndiv">
                              <FontAwesomeIcon
                                icon={faPhone}
                                className="icon"
                              />
                            </div>
                            <a
                              href={`tel:${app_setup?.contact_no}`}
                              className="text mb-0 text-decoration-none"
                            >
                              Phone: {app_setup?.contact_no}
                            </a>
                          </div>

                          <div className="d-flex align-items-center information my-4">
                            <div className="fonticndiv">
                              <FontAwesomeIcon
                                icon={faEnvelope}
                                className="icon"
                              />
                            </div>
                            <a
                              href={`mailto:${app_setup?.email}`}
                              className="text mb-0 text-decoration-none"
                            >
                              Email: {app_setup?.email}
                            </a>
                          </div>

                          <div className="d-flex align-items-center information my-4">
                            <div className="fonticndiv">
                              <FontAwesomeIcon
                                icon={faMapLocationDot}
                                className="icon"
                              />
                            </div>
                            <p
                              className="text text-decoration-underline cursor-pointer"
                              onClick={toggleMap}
                            >
                              Find Us on map
                            </p>
                          </div>

                          <a
                            target="_blank"
                            class="webwhats"
                            href="https://web.whatsapp.com/send?phone=7024945522"
                          >
                            <div className="d-flex align-items-center information my-4">
                              <div className="fonticndiv">
                                <FontAwesomeIcon
                                  icon={faWhatsappSquare}
                                  className="icon"
                                />
                              </div>
                              <p className="text mb-0">
                                {app_setup?.contact_no}
                              </p>
                            </div>
                          </a>

                          {phoneHref ? (
                            <a
                              target="_blank"
                              rel="noopener noreferrer"
                              className="mobwhats"
                              href={phoneHref}
                            >
                              <div className="d-flex align-items-center information my-4">
                                <div className="fonticndiv">
                                  <FontAwesomeIcon
                                    icon={faWhatsappSquare}
                                    className="icon"
                                  />
                                </div>
                                <p className="text mb-0">
                                  {app_setup?.alt_contact_no}
                                </p>
                              </div>
                            </a>
                          ) : (
                            // fallback UI if number is invalid
                            <div className="d-flex align-items-center information my-4">
                              <div className="fonticndiv">
                                <FontAwesomeIcon
                                  icon={faWhatsappSquare}
                                  className="icon"
                                />
                              </div>
                              <p className="text mb-0 text-danger">
                                Invalid phone number — please check the number
                                format.
                              </p>
                            </div>
                          )}
                        </div>
                      </Col>
                    </Row>
                  </div>
                </Col>
              </Row>
            )}

            <MapView
              lat={appSetup?.lat}
              lng={appSetup?.long}
              showMap={showMap}
              handle={handle}
              expandMap={expandMap}
              toggleMap={toggleMap}
            />

            {/* <FullScreen handle={handle}>
                        <div
                            className={`map ${!showMap ? "hidden" : "show"} ${handle.active ? "fullscreen" : ""
                                }`}
                        >
                            <iframe
                                className="gmap_iframe"
                                frameBorder="0"
                                scrolling="no"
                                marginHeight="0"
                                marginWidth="0"
    
                                src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d15133.39075304903!2d73.7810866!3d18.5131838!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sin!4v1719574302642!5m2!1sen!2sin"
                                title="Google Map"
                            ></iframe>
                            <div className="close">
                                <div className="map-icons">
                                    <FontAwesomeIcon
                                        icon={handle.active ? faMinimize : faMaximize}
                                        className="map_icon expand"
                                        onClick={expandMap}
                                    />
                                    <FontAwesomeIcon
                                        icon={faCircleXmark}
                                        className="map_icon close-icon"
                                        onClick={toggleMap}
                                    />
                                </div>
                            </div>
                        </div>
                    </FullScreen> */}
          </div>
        </div>
      </div>
    </section>
  );
}

export default Contact_us_Form;
