/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React, { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import AuthNextButton from "@/components/auth/AuthNextButton";
import toast from "react-hot-toast";
import AuthUserDetails from "@/components/auth/AuthUserDetails";
import SelectBox from "@/components/elements/SelectBox";
import { ICity, IProvince } from "@/types/types";
import Map, { GeolocateControl, Marker } from "react-map-gl";

import "mapbox-gl/dist/mapbox-gl.css";
import Image from "next/image";

// Validation schema using Yup
const schema = yup.object().shape({
  markerCoordinate: yup.mixed().required(" انتخاب لوکیشن الزامی است"),
  address: yup.string().required(" آدرس الزامی است"),
  cityId: yup.string().required(" انتخاب شهر الزامی است"),
  stateId: yup.string().required(" انتخاب استان الزامی است"),
});

function LocationPage() {
  const router = useRouter();
  const { request, loading } = useAxios();

  const [isCheckedOne, setIsCheckedOne] = useState(false);
  const [allStates, setAllStates] = useState<IProvince[] | null>(null);
  const [cities, setCities] = useState<ICity[] | null>(null);
  const [selectedLocation, setSelectedLocation] = useState<{
    lat: number;
    lng: number;
  } | null>(null);

  const fetchStates = async () => {
    try {
      const response = await request<{ provinces: IProvince[] }>(
        "GET",
        "/provinces"
      );
      setAllStates(response?.provinces || null);
    } catch (err) {
      console.log(err);
    }
  };

  // Fetch cities when a province is selected
  const fetchCities = async (provinceId: string) => {
    try {
      const response = await request<{ cities: ICity[] }>(
        "GET",
        `/cities/${provinceId}`
      );
      setCities(response?.cities || []);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    fetchStates();
  }, []);

  const toggleCheckBox = () => {
    setIsCheckedOne(!isCheckedOne);
  };

  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const formik = useFormik({
    initialValues: {
      markerCoordinate: [],
      address: "",
      cityId: "",
      stateId: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        await request("POST", "/verify/address", {
          mobile: mobile,
          address: values.address,
          province_id: values.stateId,
          city_id: values.cityId,
          lat: values.markerCoordinate[1],
          lng: values.markerCoordinate[0],
          show_location: isCheckedOne,
        });
        router.push("/verify/national-cart");
      } catch (err: any) {
        toast.error(err?.message || "خطای نامشخصی رخ داد.");
      } finally {
        setSubmitting(false);
      }
    },
  });

  // Handle province change
  const handleProvinceChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedProvinceId = e.target.value;
    formik.setFieldValue("stateId", selectedProvinceId);
    fetchCities(selectedProvinceId); // Fetch cities for the selected province
  };

  const handleMapClick = (event: any) => {
    const { lngLat } = event;
    setSelectedLocation({
      lat: lngLat.lat,
      lng: lngLat.lng,
    });
    formik.setFieldValue("markerCoordinate", [lngLat.lng, lngLat.lat]);
  };

  return (
    <AuthPageLayout className="address-page">
      <form
        onSubmit={formik.handleSubmit}
        className="flex w-full flex-1 flex-col items-center"
      >
        <AuthPageContent>
          <span className="text-xl font-bold">لوکیشن</span>
          <div className="mt-5">
            <AuthUserDetails />
          </div>

          <small className="font-bold mt-10 mb-4">
            مشخص کنید در کدام شهر قادر به انجام فعالیت هستید
          </small>

          <div className="w-full max-w-sm flex flex-col items-center">
          <SelectBox
            className={`mt-4 ${
              formik.touched.stateId && formik.errors.stateId
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.stateId}
            onChange={handleProvinceChange}
          >
            <option disabled value="">
              استان
            </option>
            {allStates?.map((item: IProvince) => (
              <option key={item.id} value={item.id}>
                {item?.name}
              </option>
            ))}
          </SelectBox>
          {formik.touched.stateId && formik.errors.stateId && (
            <small className="text-red-500 mt-2 block text-center">
              {formik.errors.stateId}
            </small>
          )}

          <SelectBox
            className={`mt-4 ${
              formik.touched.cityId && formik.errors.cityId
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.cityId}
            onChange={(e) => formik.setFieldValue("cityId", e.target.value)}
          >
            <option disabled value="">
              شهر
            </option>
            {cities?.map((city: ICity) => (
              <option key={city.id} value={city.id}>
                {city.name}
              </option>
            ))}
          </SelectBox>
          {formik.touched.cityId && formik.errors.cityId && (
            <small className="text-red-500 mt-2 block text-center">
              {formik.errors.cityId}
            </small>
          )}

          <textarea
            name="address"
            placeholder="آدرس"
            className={`border mt-4 w-full max-w-[300px] p-3 rounded-2xl  border-border-primary-light dark:border-border-primary-dark bg-secondary-light dark:bg-secondary-dark font-medium  ${
              formik.touched.address && formik.errors.address
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.address}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.address && formik.errors.address && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.address}
            </small>
          )}
          <Map
            style={{ height: "calc(100vh - 260px)" }}
            initialViewState={{
              longitude: 51.375433528216654,
              latitude: 35.73356434056531,
              zoom: 11,
            }}
            mapboxAccessToken="pk.eyJ1IjoiYWxkZjkyIiwiYSI6ImNscHh5ZG56dTByMXAycnJ2cDNmdDQ5M3YifQ.a_sUt1rLFMfA0jHrETcM7A"
            mapStyle="mapbox://styles/mapbox/streets-v11"
            onClick={handleMapClick}
          >
            <GeolocateControl />
            {selectedLocation && (
              <Marker
                latitude={selectedLocation.lat}
                longitude={selectedLocation.lng}
              >
                <Image
                  alt="location icon"
                  className="-mt-5"
                  width={25}
                  height={25}
                  src={"/images/icons/location.svg"}
                />
              </Marker>
            )}
          </Map>
          <label className="flex items-center gap-2">
            <input
              className="scale-125"
              type="checkbox"
              checked={isCheckedOne}
              onChange={toggleCheckBox}
            />
            <span className="text-xs font-bold">
              اطلاعات لوکیشن شما برای همه قابل نمایش باشد
            </span>
          </label>
          </div>
        </AuthPageContent>

        <AuthFormFooter onSkip={() => router.push("/verify/national-cart")}>
          <AuthNextButton type="submit" loading={loading} disabled={loading}>
            ثبت و ادامه
          </AuthNextButton>
        </AuthFormFooter>
      </form>
    </AuthPageLayout>
  );
}

export default LocationPage;
