"use client";
import React from "react";
import { Button, Col, Container, Image, Row } from "react-bootstrap";
import styles from "@/styles/Component/HalfValuation/HalfValuation.module.scss";
import { useRequest } from "@/components/App/request";
import { useRouter } from "next/navigation";
import { toastr } from "@/utils/helpers";
import { FormikProvider, useFormik, Form as FormikForm } from "formik";
import { halfValuationSchema } from "@/utils/validatonSchema/schema";
import {
  CxTextInput,
  CxTextArea
} from "@/components/default/Field/CxTextInput";
import { VehicleDetails } from "@/types/api";
import { useApp } from "@/components/App";
import ReCAPTCHA from "react-google-recaptcha";
import { useEffect, useRef, useState } from "react";
import Cookies from "js-cookie";
import { isCookiesAccepted } from "@/components/common/CookieConsent";

function HalfValuationCard({
  viewMoreBtn = false,
  open = false,
  showSecondpageData = false,
  directShowData = false,
  setOpen,
  viewCaptchaBtn = false
}) {
  useEffect(() => {
    if (directShowData) {
      setOpen(true); // Automatically expands the section if flag is true
    }
  }, [directShowData, setOpen]);

  const { state, dispatch } = useApp();
  const VEHICLE_AND_MOT_DATA = state?.VEHICLE_AND_MOT_DATA as VehicleDetails;
  console.log(
    "sVEHICLE_AND_MOT_DATA?.smmtDetails",
    VEHICLE_AND_MOT_DATA?.smmtDetails,
    "VEHICLE_AND_MOT_DATA",
    VEHICLE_AND_MOT_DATA,
    viewMoreBtn,
  );
  const recaptchaRef = useRef(null);
  const [showCaptcha, setShowCaptcha] = useState(false);
  const { request } = useRequest();

  const router = useRouter();
  const pdfFileRef = useRef<HTMLInputElement>(null);
  const numberpdfFileRef = useRef<HTMLInputElement>(null);
  
  const onSubmit = async (values, { setSubmitting }) => {
    console.log("👉 Formik values:", values);

    try {
      // Check for cookie consent
      if (!isCookiesAccepted()) {
        toastr("You must accept cookies to submit the form.", "error", "Cookies Not Accepted");
        setSubmitting(false);
        return;
      }
      // Check if cookieCountSecondPage >= cookieLimitSecondPage before processing
      const preCookieCountSecondPage = parseInt(Cookies.get("cookieCountSecondPage") || "0", 10);
      const preCookieLimit = parseInt(Cookies.get("cookieLimitSecondPage") || "0", 10);
      if (!isNaN(preCookieLimit) && preCookieCountSecondPage >= preCookieLimit) {
        dispatch({
          ...state,
          SECOND_PAGE_FORMDATA: values
        });
        router.push(`/manual-entry`);
        setSubmitting(false);
        return;
      }
      setSubmitting(true);

      // ✅ Build FormData
      const formData = new FormData();

      // Add all normal fields
      formData.append("vrm", values.vrm);
      formData.append("name", values.name);
      formData.append("email", values.email);
      formData.append("mobile", values.mobile);
      formData.append("post_code", values.post_code);
      formData.append("city", values.city);
      formData.append("additional_information", values.additional_information);

      // ✅ Attach the file
      const fileInput = pdfFileRef.current;
      const numberfileInput = numberpdfFileRef.current;
      
      
      if (fileInput?.files?.length) {
        formData.append("pdf_file", fileInput.files[0]);
        console.log("✅ Attached PDF:", fileInput.files[0]);
      } else {
        console.log("⚠️ No file selected");
      }
      if (numberfileInput?.files?.length) {
        formData.append("number_pdf_file", fileInput.files[0]);
        console.log("✅ Attached PDF:", fileInput.files[0]);
      } else {
        console.log("⚠️ No file selected");
      }

      // ✅ Now send FormData instead of JSON
      const res1 = await request("SECOND_PAGE_FORMDATA", formData);

      toastr(res1.message, "success", "Success");
      dispatch({
        ...state,
        SECOND_PAGE_FORMDATA: res1?.data ?? {}
      });
      // Increment cookieCountSecondPage after successful submit
      let cookieCountSecondPage = parseInt(Cookies.get("cookieCountSecondPage") || "0", 10);
      if (isNaN(cookieCountSecondPage)) cookieCountSecondPage = 0;
      cookieCountSecondPage += 1;
      Cookies.set("cookieCountSecondPage", cookieCountSecondPage.toString());
      // Check against limit and update isHit/ipAllowed if needed
      const cookieLimitSecondPage = parseInt(Cookies.get("cookieLimitSecondPage") || "0", 10);
      if (!isNaN(cookieLimitSecondPage) && cookieLimitSecondPage > 0 && cookieCountSecondPage >= cookieLimitSecondPage) {
        Cookies.set("isHitSecond", "false");
        dispatch({
          ...state,
          ipAllowed: false
        });
      }
      router.push("/thank-you");
    } catch (err) {
      toastr(err.message, "error", "Error Occurred");
    } finally {
      setSubmitting(false);
    }
  };

  const formik = useFormik({
    initialValues: {
      vrm: state?.vrm,
      name: "",
      email: "",
      mobile: '',
      post_code: '',
      city: "",
      additional_information: "",
      pdf_file: null, // Assuming pdf is a file input, initialized as null,
      number_pdf_file: null
    },
    validationSchema: halfValuationSchema,
    onSubmit: onSubmit
  });

  const getHitIp = async () => {
    try {
      const res = await request("USER_IP_CHECK");
      //@ts-expect-error "Invalid"
      const isAllowed = res?.data?.allowed;
      Cookies.set("isHitSecond", isAllowed);
      dispatch({
        ...state,
        ipAllowed: isAllowed
      });
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    getHitIp();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const { handleSubmit, isSubmitting } = formik;
  return (
    <>
      <div className={styles.HalfValuationBlock}>
        <Container className="bigContainer">
          <div className="vehiclechangescardBlock ">
            <div
              className={`${styles.CarBrandsCard} d-md-flex align-items-center justify-content-between`}
            >
              <div className={`${styles.ManuallyHd} d-flex align-items-center`}>
                {VEHICLE_AND_MOT_DATA.vehicleInformation?.makelogourl == null ? (<i>
                  <Image
                    style={{ width: "6rem" }}
                    src={`/assets/logos/${VEHICLE_AND_MOT_DATA.vehicleInformation?.Make}.png`}
                    alt="mazda"
                  />
                </i>) : (
                  <i>
                  <Image
                    style={{ width: "6rem" }}
                    src={`${VEHICLE_AND_MOT_DATA.vehicleInformation?.makelogourl}`}
                    alt="mazda"
                  />
                </i>
                ) }
                
                <h3>{VEHICLE_AND_MOT_DATA.vehicleInformation?.MakeModel}</h3>
              </div>

              <Button
                className={styles.ManuallyBtn}
                onClick={() => router.push("/manual-entry")}
              >
                Not your cars? <small>enter car details manually</small>
              </Button>
            </div>
            <div className={styles.HalfValuationForm}>
              <h4>For Free Valuation please fill the form below</h4>
              <FormikProvider value={formik}>
                <FormikForm onSubmit={handleSubmit}>
                  <Row>
                    <Col md={6}>
                      <CxTextInput
                        name="name"
                        required={true}
                        label="Your Name Please"
                        placeholder="Full Name"
                        maxLength={20}
                      />
                    </Col>
                    <Col md={6}>
                      <CxTextInput
                        name="email"
                        label="Email Address"
                        required={true}
                        placeholder="We will send valuation email"
                      />
                    </Col>
                    <Col md={4}>
                      <CxTextInput
                        name="mobile"
                        label="Mobile Number"
                        required={true}
                        placeholder="Carefully enter please"
                        maxLength={11}
                      />
                    </Col>
                    <Col md={4}>
                      <CxTextInput
                        name="post_code"
                        label="Enter Your post code"
                        required={true}
                        placeholder="Carefully enter half of full postcode"
                      />
                    </Col>
                    <Col md={4}>
                      <CxTextInput
                        name="city"
                        label="City"
                        required={true}
                        placeholder="City"
                        maxLength={20}
                      />
                    </Col>
                    <Col md={12}>
                      {/* <CxTextInput
                        name="additional_information"
                        label="Mechanical,  electrical or body work issue?"
                        required={true}
                        placeholder="Message to the buyer / Additional information"
                      /> */}
                      <CxTextArea
                        name="additional_information"
                        label="Mechanical,  electrical or body work issue?"
                        required={true}
                        placeholder="Message to the buyer / Additional information"
                        maxLength={300}
                      />
                    </Col>
                    <Col md={12}>
                      <input
                        name="pdf_file"
                        type="file"
                        id="pdf-upload"
                        accept="application/pdf"
                        ref={pdfFileRef}
                        hidden 
                      />
                    </Col>
                     <Col md={12}>
                      <input
                        name="number_pdf_file"
                        type="file"
                        id="number-pdf-upload"
                        accept="application/pdf"
                        ref={numberpdfFileRef}
                        hidden
                      />
                    </Col>

                    <Button
                      className="btn-custom"
                      type="submit"
                      disabled={isSubmitting}
                    >
                      Value My Car
                      <Image
                        src="../assets/cursor-icon.png"
                        alt="cursor-icon"
                      />
                    </Button>
                  </Row>
                </FormikForm>
              </FormikProvider>
            </div>

            <div className="CarImgCard">
              <Image src="/assets/carImg.png" alt="carImg" />
            </div>
            <div className="CarImgCardOne">
              <Image src="/assets/carImg1.png" alt="carImg" />
            </div>
            <div className="captcha" style={{ position: "relative" }}>
              {void console.log("showCaptcha", showCaptcha)}
              {void console.log("viewCaptchaBtn", viewCaptchaBtn)}
              {void console.log("directShowData", directShowData)}
              {void console.log("setOpen==>>>>", setOpen, open)}
              {viewCaptchaBtn && showCaptcha ? (
                <ReCAPTCHA
                  ref={recaptchaRef}
                  sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
                  onChange={() => setOpen(!open)}
                />
              ) : null}
            </div>
            {showSecondpageData ? (
              <>
                <a
                  className={styles.ViewMore}
                  onClick={() => {
                    if (!viewCaptchaBtn) {
                      setOpen(!open);
                    } else {
                      setShowCaptcha(true);
                    }
                  }}
                  aria-controls="example-collapse-text"
                  aria-expanded={open}
                  // size={"sm"}
                >
                  {!directShowData ? (!open ? "View More" : "View Less") : ""}
                </a>
              </>
            ) : (
              ""
            )}
          </div>
        </Container>
      </div>
    </>
  );
}

export default HalfValuationCard;
