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,
  faLocationDot,
  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 [sectionAnimation, setSectionAnimation] = useState("slide-left");
  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 toggleMap = () => {
    if (!showMap) {
      setSectionAnimation("slide-right");
      setShowMap(true);

      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    } else {
      setSectionAnimation("slide-left");
      setShowMap(false);

      if (handle.active) {
        handle.exit();
      }
    }
  };

  const onSubmit = (data) => {
    dispatch(contactusForm(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">
      <div className="flipIn">
        <div className="container">
          <div className="Form_section_holder">
            <Row className="justify-content-center">
              <Col xxl={10} xl={10} lg={10} md={11} sm={12}>
                <div className="heading_holder text-center">
                  <h4 className="heading_text">
                    We’re here to help you with all your farming needs.
                  </h4>
                </div>

                <div
                  key={`${showMap}-${sectionAnimation}`}
                  className={`contact_animation Information-client ${sectionAnimation}`}
                >
                  {!showMap ? (
                    <Row className="me-0 ms-0">
                      <Col
                        xxl={8}
                        xl={8}
                        lg={7}
                        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>

                                  <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-4", {
                                          "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 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={4}
                        xl={4}
                        lg={5}
                        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>

                          <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={faLocationDot}
                                  className="icon"
                                />
                              </div>
                              <p className="text mb-0">{app_setup?.address}</p>
                            </div>
                          </a>
                        </div>
                      </Col>
                    </Row>
                  ) : (
                    <div className="map_holder">
                      <MapView
                        lat={app_setup?.lat}
                        lng={app_setup?.long}
                        showMap={true}
                        handle={handle}
                        expandMap={expandMap}
                        toggleMap={toggleMap}
                      />
                    </div>
                  )}
                </div>
              </Col>
            </Row>
          </div>
        </div>
      </div>
    </section>
  );
}

export default Contact_us_Form;
