import { Button, Form, Image, Input, Modal, notification, Select } from "antd";
import cx from "classnames";
import { FC, useEffect, useRef, useState } from "react";
import styles from "./enquiryForm.module.scss";
import * as EnquiryApi from "../../../pages/api/enquiry";
import { useMediaQuery } from "react-responsive";
import { PlayCircleOutlined } from "@ant-design/icons";
import Router, { useRouter } from "next/router";
import ReCAPTCHA from "react-google-recaptcha";
import { isEmpty } from "lodash";

const EnquiryForm: FC<any> = ({ video }) => {
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [message, setMessage] = useState("");
  const [enquiryType, setEnquiryType] = useState("");
  const [isOpen, setIsOpen] = useState(false);
  const [form] = Form.useForm();
  const captchaRef = useRef<any>("");
  const router = useRouter();
  const [verified, setVerified] = useState(false);
  
  const handleClose = () => {
    setIsOpen((state) => !state);
  };

  const resetForm = () => {
    form.resetFields();
    console.log(firstName, firstName, phone, message);
  };

  const EnquirySubmit = (value: any) => {
    const params = {
      first_name: firstName,
      last_name: lastName,
      phone: phone,
      email: email,
      message: message,
      type: enquiryType,
    };

    const token = captchaRef?.current?.getValue();

    EnquiryApi.enquiryPost(params).then((res) => {
      form.resetFields();
      captchaRef?.current?.reset();

      notification.success({ message: "Enquiry Form Submitted Successfully" });
      // router.push("/home#enquiryForm", undefined, { shallow: true });
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  const validateMessages = {
    required: "Please enter your ${label}!",
  };

  const VerifyCaptcha = (value: any) => {
    setVerified(true);
  };

  useEffect(() => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);

    if (!isEmpty(details)) {
      setEmail(details?.data?.email);
      setFirstName(details?.data?.first_name);
      setLastName(details?.data?.last_name);
      setPhone(details?.data?.phone);
      form.setFieldsValue({
        email: details?.data?.email,
        PhoneNumber: details?.data?.phone,
        FirstName: details?.data?.first_name,
        lastName: details?.data?.last_name,
      });
    }
  }, []);

  return (
    <>
      <div className={styles.enguiryContainer}>
        <div className={cx("my-10 container")} id="enquiryForm">
          <div className={cx("ant-row", styles.home__enquiry_form__container)}>

            {/* Video Section - Will come second on mobile */}
            <div
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-14 ant-col-xl-12 h-full",
                styles.home__enquiry_form__video,
                styles.videoSection // Added new class for mobile ordering
              )}
            >
              <div className={styles.videoContainer}>
                <div className={styles.videoContent}>
                  <Image
                    src="/images/stock-photo-industrial-scaled 1.svg"
                    alt="Factory Background"
                    width="100%"
                    height="100%"
                    style={{ objectFit: 'cover', cursor: "pointer" }}
                  />

                  {/* Gradient Overlay */}
                  <div className={styles.gradientOverlay}></div>

                  {/* Play Button */}
                  <button className={styles.playButton} onClick={handleClose}>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className={styles.playIcon}
                      fill="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path d="M8 5v14l11-7z" />
                    </svg>
                  </button>

                  {/* Logo + Tagline */}
                  <div className={styles.videoFooter}>
                    <h1 className={styles.logoText}>
                      <span className={styles.logoPartRed}>indi</span>
                      <span className={styles.logoPartDark}>spare</span>
                    </h1>
                    <p className={styles.tagline}>
                      Countless Parts, Happy Hearts!
                    </p>
                  </div>
                </div>
              </div>
            </div>
            {/* Form Section - Will come first on mobile */}
            <Form
              layout="vertical"
              onFinish={EnquirySubmit}
              onFinishFailed={onFinishFailed}
              validateMessages={validateMessages}
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-xl-12",
                styles.home__enquiry_form__input,
                styles.formSection // Added new class for mobile ordering
              )}
              form={form}
            >
              <div className={styles.home__enquiry_form__title}>We'd Love to Hear from You!</div>
              <div className={styles.home__enquiry_form__sub_title}>
                Please fill up this form, we will get back to you shortly!
              </div>
              <div className={cx("ant-row")}>
                <Form.Item
                  label="First Name"
                  className={cx(
                    "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                    styles.inputContainer
                  )}
                  name="FirstName"
                  rules={[
                    {
                      required: true,
                    },
                  ]}
                >
                  <Input
                    value={firstName}
                    onChange={(evt) => {
                      setFirstName(evt.target.value);
                    }}
                    type="text"
                    className={styles.first_name}
                    placeholder={"First Name"}
                  />
                </Form.Item>

                <Form.Item
                  className={cx(
                    "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                    styles.inputContainer
                  )}
                  label="Last Name"
                  name="lastName"
                  rules={[{ required: true }]}
                >
                  <Input
                    value={lastName}
                    onChange={(evt) => {
                      setLastName(evt.target.value);
                    }}
                    type="text"
                    className={styles.first_name}
                    placeholder={"Last Name"}
                  />
                </Form.Item>
              </div>
              <div className={cx("ant-row")}>
                <Form.Item
                  label="Phone Number"
                  name="PhoneNumber"
                  rules={[
                    { required: true },
                    {
                      type: "string",
                      min: 10,
                      max: 10,
                      message: "Please enter a valid mobile number",
                    },
                  ]}
                  className={cx(
                    "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                    styles.inputContainer
                  )}
                >
                  <Input
                    type="number"
                    className={cx(styles.first_name, "numberInput")}
                    placeholder={"Phone"}
                    maxLength={10}
                    value={phone}
                    onChange={(evt) => {
                      setPhone(evt.target.value);
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label="Email Address"
                  name="email"
                  rules={[
                    { required: true },
                    {
                      type: "email",
                      pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
                      message: `Please enter a valid e-mail address`,
                    },
                  ]}
                  className={cx(
                    "ant-col ant-col-sm-24 ant-col-md-12 ant-col-xl-12",
                    styles.inputContainer
                  )}
                >
                  <Input
                    value={email}
                    onChange={(evt) => {
                      setEmail(evt.target.value);
                    }}
                    type="text"
                    style={{ marginBottom: "8px" }}
                    className={styles.home__enquiry_form__input_email}
                    placeholder={"Email"}
                  />
                </Form.Item>
              </div>
              <Form.Item
                label="Type Of Enquiry"
                name="EnquiryType"
                rules={[
                  { required: true, message: "Please select enquiry type!" },
                ]}
              >
                <Select
                  className={styles.typeEnquiryContainer}
                  allowClear
                  placeholder="Select Enquiry Type"
                  value={enquiryType}
                  onChange={(e: any) => setEnquiryType(e)}
                  options={[
                    {
                      value: 1,
                      label: "Product Enquiry",
                    },
                    {
                      value: 2,
                      label: "Seller Enquiry",
                    },
                    {
                      value: 3,
                      label: "Other",
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item
                label="Message"
                name="Message"
                rules={[
                  { required: true },
                  { type: "string", min: 5, max: 160 },
                ]}
              >
                <Input.TextArea
                  value={message}
                  onChange={(evt) => {
                    setMessage(evt.target.value);
                  }}
                  id="footer-newsletter-address"
                  placeholder={"Message"}
                  maxLength={160}
                  showCount
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  className={styles.home__enquiry_form__button}
                >
                 Send Inquiry
                </Button>
              </Form.Item>
            </Form>


            {isOpen ? (
              <Modal
                visible={isOpen}
                width={"100%"}
                onOk={() => {
                  setIsOpen(!isOpen);
                }}
                onCancel={() => {
                  setIsOpen(!isOpen);
                }}
                footer={null}
                style={{ height: "100%", width: "100%", top: "1em" }}
                destroyOnClose={true}
                bodyStyle={{ height: "100%" }}
                className={styles.modalStyles}
              >
                <div style={{ height: "100%", zIndex: 99999999999999 }}>
                  <iframe
                    width="100%"
                    height="100%"
                    src="https://www.youtube.com/embed/hTOBjtxMxOA?t=9s&autoplay=1&loop=1&rel=0&showinfo=0&mute=1"
                    title="YouTube video player"
                    allow=" autoplay;  encrypted-media; fullscreen"
                  />
                </div>
              </Modal>
            ) : null}
          </div>
        </div>
      </div>
    </>
  );
};
export default EnquiryForm;