"use client";

import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import styles from "@/styles/Component/Banner/Banner.module.scss";
import { Container, ListGroup, Image, Form, Button } from "react-bootstrap";
import { useFormik, FormikProvider, Form as FormikForm } from "formik";
import { carSchema } from "@/utils/validatonSchema/schema";
import { useRequest } from "@/components/App/request";
import { toastrC } from "@/utils/helpers";
import { useApp } from "@/components/App";
import Cookies from "js-cookie";
import { isCookiesAccepted } from "@/components/common/CookieConsent";

const Banner = () => {
  const { request } = useRequest();
  const { state, dispatch } = useApp();
  const router = useRouter();

  const getHitIp = async () => {
    try {
      const res = await request("USER_IP_CHECK");
      //@ts-expect-error "Invalid"
      const isAllowed = res?.data?.allowed;
      Cookies.set("isHit", isAllowed);
      dispatch({
        ...state,
        ipAllowed: isAllowed
      });
    } catch (err) {
      console.log(err);
    }
  };

  const getCookieCheck = async () => {
    try {
      const res = await request("USER_COOKIE_CHECK");

      const cookieLimit = res?.data?.[0]?.limit ?? 0;
      const cookieLimitSecondPage = res?.data?.[1]?.limit ?? 0;

      Cookies.set("cookieLimit", cookieLimit);
      Cookies.set("cookieLimitSecondPage", cookieLimitSecondPage);

      let cookieCount = parseInt(Cookies.get("cookieCount") || "0", 10);

      if (isNaN(cookieCount)) cookieCount = 0;
      // Compare count to limit
      const isAllowed = cookieCount < cookieLimit;
      Cookies.set("isHit", isAllowed ? "true" : "false");
      dispatch({
        ...state,
        ipAllowed: isAllowed
      });
      // Optionally, store the limit for reference

      if (res?.data?.[0]?.status == 0) {
        Cookies.remove("cookieCount");
        Cookies.remove("cookieLimit");
        return;
      }

      if (res?.data?.[1]?.status == 0) {
        Cookies.remove("cookieCountSecondPage");
        Cookies.remove("cookieLimitSecondPage");
        return;
      }
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    getHitIp();
    getCookieCheck();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onSubmit = async (values, { setSubmitting }) => {
    try {
      // Check for cookie consent
      if (!isCookiesAccepted()) {
        toastrC(
          "You must accept cookies to check the VRM no.",
          "error",
          "Cookies Not Accepted"
        );
        setSubmitting(false);
        return;
      }

      const vrmNo = values.vrm.replace(/\s+/g, "");
      values.vrm = vrmNo;

      if (!state.ipAllowed) {
        dispatch({
          ...state,
          vrm: vrmNo,
          mileage: values.mileage
        });
        router.push(`/manual-entry`);
        return;
      }
      // Check if cookieCount >= cookieLimit before processing
      const preCookieCount = parseInt(Cookies.get("cookieCount") || "0", 10);
      const preCookieLimit = parseInt(Cookies.get("cookieLimit") || "0", 10);
      if (
        !isNaN(preCookieLimit) &&
        preCookieLimit > 0 &&
        preCookieCount >= preCookieLimit
      ) {
        dispatch({
          ...state,
          vrm: values.vrm,
          mileage: values.mileage
        });
        router.push(`/manual-entry`);
        setSubmitting(false);
        return;
      }
      setSubmitting(true);
      const [res1, res2] = await Promise.all([
        await request("VEHICLE_AND_MOT_DATA", values),
        await request("ROAD_TAX_MOT_DATA", values)
      ]);
      // toastrC(res1.message, "success", "Success");
      dispatch({
        ...state,
        VEHICLE_AND_MOT_DATA: res1?.data ?? null,
        ROAD_TAX_MOT_DATA: res2?.data ?? null,
        vrm: vrmNo,
        mileage: values.mileage
      });
      // Increment cookieCount after successful VRM check
      let cookieCount = parseInt(Cookies.get("cookieCount") || "0", 10);
      if (isNaN(cookieCount)) cookieCount = 0;
      cookieCount += 1;
      Cookies.set("cookieCount", cookieCount.toString());
      // Check against limit and update isHit/ipAllowed if needed
      const cookieLimit = parseInt(Cookies.get("cookieLimit") || "0", 10);
      if (
        !isNaN(cookieLimit) &&
        cookieLimit > 0 &&
        cookieCount >= cookieLimit
      ) {
        Cookies.set("isHit", "false");
        dispatch({
          ...state,
          ipAllowed: false
        });
      }
      if (res1.data) {
        setTimeout(() => {
          router.push(`/full-valuation`);
        }, 200);
      } else {
        setTimeout(() => {
          router.push(`/manual-entry`);
        }, 200);
      }
    } catch (err) {
      console.log("onSubmit", err);
      toastrC(err.message, "error", "Error Occurred");
    } finally {
      setSubmitting(false);
    }
  };

  const formik = useFormik({
    initialValues: {
      vrm: "",
      mileage: 0
    },
    validationSchema: carSchema,
    onSubmit: onSubmit
  });

  const { handleSubmit, handleChange, isSubmitting } = formik;

  return (
    <div className={`${styles.bannerCard} text-center`}>
      <Container>
        <div className={styles.bannerTop}>
          <h1>Sell Your Car Easy, Safe & Fast</h1>
          <div className={`${styles.subTitle}`}>
            {" "}
            <span>FREE</span> CAR VALUATION
          </div>
          <ListGroup
            as="ul"
            className={`${styles.bannerList}  d-flex flex-row align-items-center  justify-content-center   justify-content-lg-between flex-wrap`}
          >
            <ListGroup.Item as="li">FREE COLLECTION </ListGroup.Item>
            <ListGroup.Item as="li">NO ADMIN CHARGES</ListGroup.Item>
            <ListGroup.Item as="li"> ADVANCE PAYMENT</ListGroup.Item>
          </ListGroup>
        </div>
        <div className={`${styles.bannerMiddle} `}>
          <FormikProvider value={formik}>
            <FormikForm onSubmit={handleSubmit}>
              <Form.Group className="mb-3" controlId="formBasicEmail">
                <div className={styles.enterRegBox}>
                  <Image src="../assets/enter-reg.png" alt="enter-reg" />
                  <Form.Control
                    className={`${styles.regInput}`}
                    type="text"
                    placeholder="Enter reg no"
                    name="vrm"
                    onChange={handleChange}
                  />
                </div>
                {formik.touched.vrm && formik.errors.vrm ? (
                  <div className="text-danger">
                    {formik.errors.vrm as string}
                  </div>
                ) : null}
                <div className={styles.enterRegBox}>
                  <Form.Control
                    type="number"
                    placeholder="Enter mileage"
                    name="mileage"
                    onChange={handleChange}
                  />
                </div>
                {formik.touched.mileage && formik.errors.mileage ? (
                  <div className="text-danger">
                    {formik.errors.mileage as string}
                  </div>
                ) : null}
                <Button
                  className={`btn-custom`}
                  type="submit"
                  disabled={isSubmitting}
                  style={{
                    cursor: isSubmitting ? "not-allowed" : "pointer"
                  }}
                >
                  Value My Car{" "}
                  <Image src="../assets/cursor-icon.png" alt="cursor-icon" />
                </Button>
              </Form.Group>
            </FormikForm>
          </FormikProvider>
        </div>
      </Container>
      <div className={styles.bannerBottom}>
        <Image src="../assets/banner-car01.png" alt="banner-car01" />
        <Image src="../assets/banner-car02.png" alt="banner-car01" />
      </div>
    </div>
  );
};
export default Banner;
