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

import Container from "@/components/elements/Container";
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 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";
import { useUser } from "@/hooks/useUser";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { useTranslation } from "react-i18next";
import { useMemo } from "react";

function LocationPage() {
  const { t } = useTranslation("common");
  const schema = useMemo(
    () =>
      yup.object().shape({
        markerCoordinate: yup.mixed().required(t("settings.edit.location.markerRequired")),
        address: yup.string().required(t("settings.edit.location.addressRequired")),
        cityId: yup.string().required(t("settings.edit.location.cityRequired")),
        stateId: yup.string().required(t("settings.edit.location.stateRequired")),
      }),
    [t]
  );
  const router = useRouter();
  const { request, loading } = useAxios();
  const user = useUser();

  const [isCheckedOne, setIsCheckedOne] = useState<boolean | null>(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);
      // console.log(response?.provinces);
    } 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 formik = useFormik({
    initialValues: {
      markerCoordinate: [] as number[],
      address: "",
      cityId: "",
      stateId: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        await request("PATCH", "/verify/address", {
          address: values.address,
          province_id: values.stateId,
          city_id: values.cityId,
          lat: values.markerCoordinate[1],
          lng: values.markerCoordinate[0],
          show_location: isCheckedOne,
        });
        router.push("/settings/edit");
      } catch (err: any) {
        toast.error(err?.message || t("settings.edit.unknownError"));
      } 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]);
  };
  useEffect(() => {
    if (user) {
      formik.setValues({
        markerCoordinate:
          user.lat && user.lng
            ? [Number(user.lng), Number(user.lat)]
            : [],
        address: user.address || "",
        cityId: user?.city?.id ? String(user.city.id) : "",
        stateId: user?.province?.id ? String(user.province.id) : "",
      });

      if (user.lat && user.lng) {
        setSelectedLocation({
          lat: Number(user.lat),
          lng: Number(user.lng),
        });
      }

      if (user?.province?.id) {
        fetchCities(user?.province?.id.toString());
      }
      if (user?.show_location !== undefined) {
        setIsCheckedOne(user?.show_location);
      }
    }
  }, [user]);

  return (
    <LocalePageShell>
    <Container>
      <div className="p-4 flex flex-col items-center  justify-center address-page ">
        <span className="text-xl font-bold text-foreground">{t("settings.edit.nav.location")}</span>
        <div className="mt-5"></div>

        <small className="font-bold mt-10 mb-4">
          {t("settings.edit.location.question")}
        </small>
        <form
          onSubmit={formik.handleSubmit}
          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="">
              {t("settings.profile.province")}
            </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="">
              {t("settings.profile.city")}
            </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={t("settings.edit.location.addressPlaceholder")}
            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: Number(user?.lng) || 51.375433528216654,
              latitude: Number(user?.lat) || 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"
              onChange={toggleCheckBox}
              checked={isCheckedOne || false}
            />
            <span className="text-xs font-bold">
              {t("settings.edit.location.showToAll")}
            </span>
          </label>
          <AuthNextButton type="submit" className="mt-20" loading={loading} disabled={loading}>
            {t("settings.edit.save")}
          </AuthNextButton>
        </form>
      </div>
    </Container>
    </LocalePageShell>
  );
}

export default LocationPage;
