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

import React, { useEffect, useState, useCallback, useMemo } from "react";
import dynamic from "next/dynamic";
import Container from "@/components/elements/Container";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import "mapbox-gl/dist/mapbox-gl.css";
import AuthNextButton from "@/components/auth/AuthNextButton";
import Cookies from "js-cookie";
import {
  IAdvertisingCategory,
  IAdvertisingProfile,
  ICity,
  IProvince,
} from "@/types/types";
import AvatarUploader from "@/components/settings/my-billboards/Profile/AvatarUploader";
import ProfileBasicFields from "@/components/settings/my-billboards/Profile/ProfileBasicFields";
import ContactInfoFields from "@/components/settings/my-billboards/Profile/ContactInfoFields";
import AddressFields from "@/components/settings/my-billboards/Profile/AddressFields";
import Image from "next/image";
import { BASE_URL } from "@/components/main/BaseUrl";
import axios from "axios";

// Lazy load Map and related components
const Map = dynamic(() => import("react-map-gl").then((mod) => mod.Map), {
  ssr: false,
});
const Marker = dynamic(() => import("react-map-gl").then((mod) => mod.Marker), {
  ssr: false,
});
const GeolocateControl = dynamic(
  () => import("react-map-gl").then((mod) => mod.GeolocateControl),
  { ssr: false }
);

// تعریف اسکیمای اعتبارسنجی Yup
const schema = yup.object().shape({
  markerCoordinate: yup
    .array()
    .of(yup.number())
    .length(2, "مختصات باید شامل طول و عرض جغرافیایی باشد")
    .required("انتخاب لوکیشن الزامی است"),
  address: yup.string().nullable(),
  neighbourhood: yup.string().nullable(),
  cityId: yup.string().nullable(),
  stateId: yup.string().nullable(),
  vitrine_name: yup.string().nullable(),
  categoryId: yup.string().nullable(),
  about_us: yup.string().nullable(),
  phone: yup.string().nullable(),
  mobile: yup.string().nullable(),
  telegramLink: yup.string().nullable(),
  whatsappNumber: yup.string().nullable(),
  instagramLink: yup.string().nullable(),
});

interface ApiResponse {
  profileDetails: IAdvertisingProfile;
}

interface IEditProps {
  params: Promise<{ id: string; username: string }>;
}

function EditAdProfile({ params }: IEditProps) {
  const router = useRouter();
  const { request, loading } = useAxios();
  const resolvedParams = React.use(params);
  const { id } = resolvedParams;

  const [avatar, setAvatar] = useState<string | null>(null);
  const [allStates, setAllStates] = useState<IProvince[] | null>(null);
  const [cities, setCities] = useState<ICity[] | null>(null);
  const [profile, setProfile] = useState<IAdvertisingProfile | null>(null);
  const [categories, setCategories] = useState<IAdvertisingCategory[]>([]);
  const [selectedLocation, setSelectedLocation] = useState<{
    lat: number;
    lng: number;
  } | null>(null);

  // دریافت دسته‌بندی‌ها
  const fetchCategories = useCallback(async () => {
    try {
      const response = await request<{ categories: IAdvertisingCategory[] }>(
        "GET",
        "/advertising/categories"
      );
      setCategories(response?.categories ?? []);
    } catch (err) {
      console.error("Error fetching categories:", err);
      toast.error("خطا در بارگذاری دسته‌بندی‌ها");
    }
  }, [request]);

  // دریافت پروفایل
  const fetchProfile = useCallback(async () => {
    try {
      const response = await request<ApiResponse>(
        "GET",
        `/advertising/profile-web?vitrineId=${id}`
      );
      setProfile(response?.profileDetails ?? null);
    } catch (err) {
      console.error("Error fetching profile:", err);
      toast.error("خطا در بارگذاری پروفایل");
    }
  }, [id, request]);

  // دریافت استان‌ها
  const fetchStates = useCallback(async () => {
    try {
      const response = await request<{ provinces: IProvince[] }>(
        "GET",
        "/provinces"
      );
      setAllStates(response?.provinces ?? null);
    } catch (err) {
      console.error("Error fetching provinces:", err);
      toast.error("خطا در بارگذاری استان‌ها");
    }
  }, [request]);

  // دریافت شهرها
  const fetchCities = useCallback(
    async (provinceId: string) => {
      try {
        const response = await request<{ cities: ICity[] }>(
          "GET",
          `/cities/${provinceId}`
        );
        setCities(response?.cities ?? []);
      } catch (err) {
        console.error("Error fetching cities:", err);
        toast.error("خطا در بارگذاری شهرها");
      }
    },
    [request]
  );

  // انتخاب و حذف تصویر
  const selectImage = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      if (event.target.files?.[0]) {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => setAvatar(reader.result as string);
        reader.readAsDataURL(file);
      }
    },
    []
  );

  const removeImage = useCallback(() => {
    setAvatar(null);
  }, []);

  const formik = useFormik({
    initialValues: {
      markerCoordinate: [] as number[],
      address: "",
      neighbourhood: "",
      cityId: "",
      stateId: "",
      vitrine_name: "",
      categoryId: "",
      about_us: "",
      phone: "",
      mobile: "",
      telegramLink: "",
      whatsappNumber: "",
      instagramLink: "",
    },
    validationSchema: schema,
    onSubmit: async (values, { setSubmitting }) => {
      try {
        const formData = new FormData();
        const fileInput = document.getElementById("fileInput") as HTMLInputElement;
        if (fileInput?.files?.[0]) {
          formData.append("profile_image", fileInput.files[0]);
        }

        formData.append("address", values.address ?? "");
        formData.append("province", values.stateId ?? "");
        formData.append("city", values.cityId ?? "");
        formData.append("neighbourhood", values.neighbourhood ?? "");

        if (values.markerCoordinate?.[0] && values.markerCoordinate?.[1]) {
          formData.append("lat", values.markerCoordinate[0].toString());
          formData.append("lng", values.markerCoordinate[1].toString());
        }

        formData.append("vitrine_name", values.vitrine_name ?? "");
        formData.append("category", values.categoryId ?? "");
        formData.append("about_us", values.about_us ?? "");
        formData.append("contactInfo[phone]", values.phone ?? "");
        formData.append("contactInfo[mobile]", values.mobile ?? "");
        formData.append("contactInfo[telegramLink]", values.telegramLink ?? "");
        formData.append("contactInfo[whatsappNumber]", values.whatsappNumber ?? "");
        formData.append("contactInfo[instagramLink]", values.instagramLink ?? "");

        const token = Cookies.get("token");

       await axios.patch(
          `${BASE_URL}/advertising/profile`,
          formData,
          {
            headers: {
              "Authorization": `Bearer ${token}`,
              "Content-Type": "multipart/form-data",
            },
          }
        );

        toast.success("پروفایل با موفقیت به‌روزرسانی شد");
        router.push("/settings");
      } catch (error: any) {
        console.error("Submit error:", error);
        toast.error(error?.response?.data?.message || "خطا در به‌روزرسانی پروفایل");
      } finally {
        setSubmitting(false);
      }
    },
  });
  // هندل تغییر استان
  const handleProvinceChange = useCallback(
    (e: React.ChangeEvent<HTMLSelectElement>) => {
      const selectedProvinceId = e.target.value;
      formik.setFieldValue("stateId", selectedProvinceId);
      formik.setFieldValue("cityId", ""); // ریست شهر هنگام تغییر استان
      if (selectedProvinceId) {
        fetchCities(selectedProvinceId);
      } else {
        setCities(null);
      }
    },
    [fetchCities, formik]
  );

  // هندل کلیک روی نقشه
  const handleMapClick = useCallback(
    (event: any) => {
      // Note: For better typing, import MapMouseEvent if possible
      const { lngLat } = event;
      setSelectedLocation({ lat: lngLat.lat, lng: lngLat.lng });
      formik.setFieldValue("markerCoordinate", [lngLat.lat, lngLat.lng]);
    },
    [formik]
  );

  // به‌روزرسانی مقادیر فرم و موقعیت نقشه هنگام دریافت پروفایل
  useEffect(() => {
    if (profile) {
      setAvatar(profile.profile_image || null);
      formik.setValues({
        markerCoordinate:
          profile.lat &&
          profile.lng &&
          !isNaN(Number(profile.lat)) &&
          !isNaN(Number(profile.lng))
            ? [Number(profile.lat), Number(profile.lng)]
            : [],
        address: profile.address || "",
        cityId: profile.city?.id ? String(profile.city.id) : "",
        stateId: profile.province?.id ? String(profile.province.id) : "",
        neighbourhood: profile.neighbourhood || "",
        vitrine_name: profile.vitrine_name || "",
        categoryId: profile.category || "",
        about_us: profile.about_us || "",
        phone: profile.contactInfo?.phone || "",
        mobile: profile.contactInfo?.mobile || "",
        telegramLink: profile.contactInfo?.telegramLink || "",
        whatsappNumber: profile.contactInfo?.whatsappNumber || "",
        instagramLink: profile.contactInfo?.instagramLink || "",
      });

      if (
        profile.lat &&
        profile.lng &&
        !isNaN(Number(profile.lat)) &&
        !isNaN(Number(profile.lng))
      ) {
        setSelectedLocation({
          lat: Number(profile.lat),
          lng: Number(profile.lng),
        });
      }
      if (profile.province?.id) {
        fetchCities(String(profile.province.id));
      }
    }
  }, [profile, fetchCities]);

  // بارگذاری اولیه داده‌ها
  useEffect(() => {
    fetchStates();
    fetchCategories();
    fetchProfile();
  }, [fetchStates, fetchCategories, fetchProfile]);

  // بهینه‌سازی رندر نقشه با useMemo
  const mapInitialViewState = useMemo(
    () => ({
      longitude: Number(profile?.lng) || 51.375433528216654,
      latitude: Number(profile?.lat) || 35.73356434056531,
      zoom: 11,
    }),
    [profile?.lat, profile?.lng]
  );

  // Memoize the Marker to prevent unnecessary re-renders
  const memoizedMarker = useMemo(() => {
    if (!selectedLocation) return null;
    return (
      <Marker latitude={selectedLocation.lat} longitude={selectedLocation.lng}>
        <Image
          alt="آیکون مکان"
          className="-mt-5"
          width={25}
          height={25}
          src="/images/icons/location.svg"
        />
      </Marker>
    );
  }, [selectedLocation]);

  return (
    <Container>
      <div
        className="p-4 flex flex-col items-center justify-center address-page"
        aria-label="صفحه ویرایش پروفایل ویترین"
      >
        <span className="text-xl font-bold">ویرایش پروفایل ویترین</span>
        <div className="mt-5" />
        <form
          onSubmit={formik.handleSubmit}
          className="w-full max-w-sm flex flex-col items-center"
          aria-label="فرم ویرایش پروفایل"
        >
          <AvatarUploader
            avatar={avatar}
            onSelectImage={selectImage}
            onRemoveImage={removeImage}
          />
          <hr className="my-2" />
          <ProfileBasicFields formik={formik} categories={categories} />
          <hr className="my-2" />
          <ContactInfoFields formik={formik} />
          <hr className="my-2" />
          <AddressFields
            formik={formik}
            provinces={allStates}
            cities={cities}
            onProvinceChange={handleProvinceChange}
          />
          <Map
            style={{ height: "calc(100vh - 260px)" }}
            initialViewState={mapInitialViewState}
            aria-label="نقشه انتخاب مکان"
            reuseMaps // بهینه‌سازی برای جلوگیری از re-mounting مکرر
            mapboxAccessToken="pk.eyJ1IjoiYWxkZjkyIiwiYSI6ImNscHh5ZG56dTByMXAycnJ2cDNmdDQ5M3YifQ.a_sUt1rLFMfA0jHrETcM7A"
            mapStyle="mapbox://styles/mapbox/streets-v11"
            onClick={handleMapClick}
          >
            <GeolocateControl />
            {memoizedMarker}
          </Map>
          <AuthNextButton type="submit" className="mt-20" disabled={loading}>
            {loading ? "در حال ارسال..." : "ویرایش"}
          </AuthNextButton>
        </form>
      </div>
    </Container>
  );
}

export default EditAdProfile;
