/* eslint-disable @typescript-eslint/no-explicit-any */
import { ICity, IProvince } from "@/types/types";
import SelectBox from "@/components/elements/SelectBox";
import { useState, useEffect } from "react";
import useAxios from "@/hooks/useAxios";
import RoundedInput from "@/components/elements/RoundedInput";
import Map, { GeolocateControl, Marker } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import Image from "next/image";
import { useBillboardForm } from "@/contexts/BillboardFormContext";

interface LocationSelectorProps {
  formik: any;
}

const LocationSelector: React.FC<LocationSelectorProps> = ({ formik }) => {
  const { formData } = useBillboardForm();

  const { request } = useAxios();
  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);
    }
  };

  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();
  }, []);

  useEffect(() => {
    if (formik.values.stateId) {
      fetchCities(formik.values.stateId);
    }

    if (formData?.markerCoordinate && formData?.markerCoordinate[1]) {
      setSelectedLocation({
        lat: Number(formData?.markerCoordinate[1]),
        lng: Number(formData?.markerCoordinate[0]),
      });
    }
  }, [formik?.values?.markerCoordinate]);

  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 (
    <>
      <SelectBox
        className={`max-w-full ${
          formik.touched.stateId && formik.errors.stateId
            ? "border-red-500 dark:border-red-500"
            : ""
        }`}
        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 block text-center">
          {formik.errors.stateId}
        </small>
      )}

      <SelectBox
        className={`max-w-full ${
          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 block text-center">
          {formik.errors.cityId}
        </small>
      )}
      <RoundedInput
        className={`max-w-full ${
          formik.touched.neighbourhood && formik.errors.neighbourhood
            ? "border-red-500 dark:border-red-500"
            : ""
        }`}
        type="text"
        placeholder="محله "
        {...formik.getFieldProps("neighbourhood")}
      />

      {formik.touched.neighbourhood && formik.errors.neighbourhood && (
        <p className="text-red-500">{formik.errors.neighbourhood}</p>
      )}
      <textarea
         //className={`w-full p-4 mt-2 h-24 rounded-3xl border border-border-secondary-light dark:border-border-secondary-dark bg-secondary-light dark:bg-secondary-dark font-medium`}
        className={`w-full p-4 mt-2 h-24 rounded-3xl border 
          ${
            formik.touched.address && formik.errors.address
              ? "border-red-500 dark:border-red-500"
              : "border-border-primary-light dark:border-border-primary-dark"
          }
          border-neutral-950 text-neutral-900 dark:text-neutral-50 dark:border-neutral-400 font-medium`}
        placeholder="آدرس"
        {...formik.getFieldProps("address")}
      ></textarea>
      {formik.touched.address && formik.errors.address && (
        <p className="text-red-500">{formik.errors.address}</p>
      )}
      <div className="w-full rounded-2xl overflow-hidden mt-2">
        <Map
          style={{ height: "240px" }}
          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>
        {formik.touched.markerCoordinate && formik.errors.markerCoordinate && (
          <p className="text-red-500 text-xs">
            {formik.errors.markerCoordinate as string}
          </p>
        )}
      </div>
    </>
  );
};

export default LocationSelector;
