import React, {
  useEffect,
  useState,
  useMemo,
  useCallback,
  memo,
  useRef,
} from "react";
import Map, { Marker, Popup } from "react-map-gl/maplibre";
import "maplibre-gl/dist/maplibre-gl.css";
import { useUserProfileStore } from "../context/zustand-store/userStore";
import { getLocationByProvince } from "../utils/getLocationByProvince";
import {
  MapPinIcon,
  GlobeAltIcon,
  FunnelIcon,
  MagnifyingGlassIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import Typography from "../components/Typography/Typography";
import { useModalStore } from "../context/zustand-store/appStore";
import { useApiRequest } from "../utils/useApiRequest";
import { getPosSellStatus } from "../utils/getPosSellStatus";
import { formatJustDate } from "../utils/formatTime";
import MainPlaceInfo from "../partials/main/MainPlaceInfo";
import { getSystemBaseAddress } from "../utils/getSystemBaseAddress";

// Types
interface StewardItem {
  lat: number;
  lng: number;
  guilds_name?: string;
  session_last_seen_date?: string;
  pos?: {
    products?: Array<{
      real_allocated_weight?: string;
      total_carcasses_weight?: string;
    }>;
  };
  [key: string]: any;
}

interface PoultryItem {
  Lat: number;
  Long: number;
  unit_name?: string;
  [key: string]: any;
}

interface LivestockItem {
  lot: number;
  lng: number;
  fullname?: string;
  [key: string]: any;
}

// Custom hook for location
const useCurrentLocation = () => {
  const [location, setLocation] = useState<[number, number] | []>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!navigator?.geolocation) {
      setIsLoading(false);
      return;
    }

    const timeoutId = setTimeout(() => {
      setIsLoading(false);
    }, 5000);

    navigator.geolocation.getCurrentPosition(
      (position) => {
        clearTimeout(timeoutId);
        setLocation([position.coords.latitude, position.coords.longitude]);
        setIsLoading(false);
      },
      () => {
        clearTimeout(timeoutId);
        setIsLoading(false);
      },
      { timeout: 5000, enableHighAccuracy: false }
    );

    return () => clearTimeout(timeoutId);
  }, []);

  return { location, isLoading };
};

// Custom hook for map data
const useMapData = (
  province: string | undefined,
  filters: {
    showStewards: boolean;
    showPoultries: boolean;
    showLiveStocks: boolean;
  }
) => {
  const stewardsApiUrl = useMemo(
    () =>
      province
        ? `${getSystemBaseAddress(province)}pos_register_session_inspection/`
        : "",
    [province]
  );

  const poultryApiUrl = useMemo(
    () =>
      province
        ? `https://${
            province === "hamedan" ? "ha" : "ma"
          }backend.rasadyar.com/poultry-loc/`
        : "",
    [province]
  );

  const livestockApiUrl = useMemo(
    () =>
      province
        ? `https://habackend.rasadyar.com/LiveStock/rancher/bazrasi-rancher-view?type=industrial`
        : "",
    [province]
  );

  const { data: stewardsData } = useApiRequest<StewardItem[]>({
    api: stewardsApiUrl,
    enabled: !!province && filters.showStewards && !!stewardsApiUrl,
    disableBackdrop: true,
    queryKey: ["stewards", province, filters.showStewards],
  });

  const { data: poultryData } = useApiRequest<PoultryItem[]>({
    api: poultryApiUrl,
    enabled: !!province && filters.showPoultries && !!poultryApiUrl,
    disableBackdrop: true,
    queryKey: ["poultry", province, filters.showPoultries],
  });

  const { data: livestockData } = useApiRequest<LivestockItem[]>({
    api: livestockApiUrl,
    enabled: !!province && filters.showLiveStocks && !!livestockApiUrl,
    disableBackdrop: true,
    queryKey: ["livestock", province, filters.showLiveStocks],
  });

  return { stewardsData, poultryData, livestockData };
};

// Memoized Location Button
const LocationButton = memo(
  ({
    currentLocation,
    onLocationClick,
  }: {
    currentLocation: [number, number] | [];
    onLocationClick: () => void;
  }) => {
    if (currentLocation.length === 0) return null;

    return (
      <div className="absolute bottom-16 right-3 sm:right-4 z-[100]">
        <button
          onClick={onLocationClick}
          className="group relative bg-gradient-to-br from-white/95 to-white/85 backdrop-blur-xl shadow-lg hover:shadow-xl border border-white/20 rounded-xl p-2.5 sm:p-3 transition-all duration-300 hover:scale-105 active:scale-95"
          aria-label="موقعیت فعلی"
        >
          <div className="absolute inset-0 bg-gradient-to-br from-primary-500/10 to-primary-600/5 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          <MapPinIcon className="relative w-5 h-5 sm:w-6 sm:h-6 text-primary-600 group-hover:text-primary-700 transition-colors duration-300" />
        </button>
      </div>
    );
  }
);
LocationButton.displayName = "LocationButton";

// Memoized Province Button
const ProvinceButton = memo(
  ({ onProvinceClick }: { onProvinceClick: () => void }) => {
    return (
      <div className="absolute bottom-16 right-14 sm:right-20 z-[100]">
        <button
          onClick={onProvinceClick}
          className="group relative bg-gradient-to-br from-white/95 to-white/85 backdrop-blur-xl shadow-lg hover:shadow-xl border border-white/20 rounded-xl p-2.5 sm:p-3 transition-all duration-300 hover:scale-105 active:scale-95"
          aria-label="نمایش استان"
        >
          <div className="absolute inset-0 bg-gradient-to-br from-primary-500/10 to-primary-600/5 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          <GlobeAltIcon className="relative w-5 h-5 sm:w-6 sm:h-6 text-primary-600 group-hover:text-primary-700 transition-colors duration-300" />
        </button>
      </div>
    );
  }
);
ProvinceButton.displayName = "ProvinceButton";

// Memoized Steward Marker with lightweight CSS markers
const StewardMarker = memo(
  ({
    item,
    onMarkerClick,
  }: {
    item: StewardItem;
    onMarkerClick: (item: StewardItem) => void;
  }) => {
    const status = useMemo(() => getPosSellStatus(item), [item]);
    const markerColor = useMemo(() => {
      if (status <= 70) return "#22c55e"; // green
      if (status <= 30) return "#f97316"; // orange
      if (status < 0) return "#eab308"; // yellow
      return "#ef4444"; // red
    }, [status]);

    const guildName = item?.guilds_name || "نامشخص";

    const handleMarkerClick = () => {
      onMarkerClick(item);
    };

    return (
      <>
        <Marker longitude={item.lng} latitude={item.lat} anchor="bottom">
          <div
            style={{
              width: "16px",
              height: "16px",
              borderRadius: "50%",
              backgroundColor: markerColor,
              border: "2px solid white",
              cursor: "pointer",
            }}
            onClick={handleMarkerClick}
          />
        </Marker>
        <Popup
          longitude={item.lng}
          latitude={item.lat}
          anchor="top"
          closeButton={false}
          closeOnClick={false}
          className="custom-popup"
          style={{ padding: 0, pointerEvents: "none" }}
        >
          <div
            className="modern-tooltip-content"
            style={{ margin: 0, pointerEvents: "none" }}
          >
            {guildName}
          </div>
        </Popup>
      </>
    );
  }
);
StewardMarker.displayName = "StewardMarker";

// Memoized Poultry Marker with lightweight CSS markers
const PoultryMarker = memo(({ item }: { item: PoultryItem }) => {
  const [showPopup, setShowPopup] = useState(false);
  const unitName = item?.unit_name || "نامشخص";

  return (
    <>
      <Marker longitude={item.Long} latitude={item.Lat} anchor="bottom">
        <div
          style={{
            width: "24px",
            height: "24px",
            borderRadius: "50%",
            backgroundColor: "#fbbf24",
            border: "2px solid white",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "14px",
            cursor: "pointer",
          }}
          onClick={() => setShowPopup(true)}
        >
          🐔
        </div>
      </Marker>
      <Popup
        longitude={item.Long}
        latitude={item.Lat}
        anchor="top"
        closeButton={false}
        closeOnClick={false}
        className="custom-popup"
        style={{ padding: 0, pointerEvents: "none" }}
      >
        <div
          className="modern-tooltip-content"
          style={{ margin: 0, pointerEvents: "none" }}
        >
          {unitName}
        </div>
      </Popup>
      {showPopup && (
        <Popup
          longitude={item.Long}
          latitude={item.Lat}
          anchor="bottom"
          onClose={() => setShowPopup(false)}
          closeButton={false}
          className="custom-popup"
        >
          <MainPlaceInfo item={item} isPoultry />
        </Popup>
      )}
    </>
  );
});
PoultryMarker.displayName = "PoultryMarker";

// Memoized Livestock Marker with smooth animations
const LivestockMarker = memo(({ item }: { item: LivestockItem }) => {
  const [showPopup, setShowPopup] = useState(false);
  const fullname = item?.fullname?.replace(":", " ") || "نامشخص";

  return (
    <>
      <Marker longitude={item.lng} latitude={item.lot} anchor="bottom">
        <div
          style={{
            width: "24px",
            height: "24px",
            borderRadius: "50%",
            backgroundColor: "#84cc16",
            border: "2px solid white",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "14px",
            cursor: "pointer",
          }}
          onClick={() => setShowPopup(true)}
        >
          🐑
        </div>
      </Marker>
      <Popup
        longitude={item.lng}
        latitude={item.lot}
        anchor="top"
        closeButton={false}
        closeOnClick={false}
        className="custom-popup"
        style={{ padding: 0, pointerEvents: "none" }}
      >
        <div
          className="modern-tooltip-content"
          style={{ margin: 0, pointerEvents: "none" }}
        >
          {fullname}
        </div>
      </Popup>
      {showPopup && (
        <Popup
          longitude={item.lng}
          latitude={item.lot}
          anchor="bottom"
          onClose={() => setShowPopup(false)}
          closeButton={false}
          className="custom-popup"
        >
          <MainPlaceInfo item={item} isLivestock />
        </Popup>
      )}
    </>
  );
});
LivestockMarker.displayName = "LivestockMarker";

// Memoized Current Location Marker with lightweight CSS
const CurrentLocationMarker = memo(
  ({
    location,
    inspectorName,
  }: {
    location: [number, number];
    inspectorName?: string;
  }) => {
    return (
      <>
        <Marker longitude={location[1]} latitude={location[0]} anchor="bottom">
          <div
            style={{
              width: "32px",
              height: "32px",
              borderRadius: "50%",
              backgroundColor: "#3b82f6",
              border: "3px solid white",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "18px",
            }}
          >
            📍
          </div>
        </Marker>
        <Popup
          longitude={location[1]}
          latitude={location[0]}
          anchor="top"
          closeButton={false}
          closeOnClick={false}
          className="custom-popup"
          style={{ padding: 0, pointerEvents: "none" }}
        >
          <div
            className="modern-tooltip-content modern-tooltip-primary"
            style={{ margin: 0, pointerEvents: "none" }}
          >
            بازرس {inspectorName || "نامشخص"}
          </div>
        </Popup>
      </>
    );
  }
);
CurrentLocationMarker.displayName = "CurrentLocationMarker";

// Memoized Toggle Button
const ToggleButton = memo(
  ({
    label,
    isActive,
    onClick,
    icon,
  }: {
    label: string;
    isActive: boolean;
    onClick: () => void;
    icon?: React.ReactNode;
  }) => {
    return (
      <button
        onClick={onClick}
        className={`
          group relative overflow-hidden w-full
          px-5 py-3.5 rounded-xl
          font-semibold text-sm
          transition-all duration-300 ease-out
          transform hover:scale-[1.02] active:scale-[0.98]
          backdrop-blur-xl border-2
          ${
            isActive
              ? "bg-gradient-to-r from-primary-500 via-primary-600 to-primary-500 text-white shadow-sm shadow-primary-500/40 border-primary-400/50"
              : "bg-gradient-to-br from-white to-gray-50 dark:from-gray-800 dark:to-gray-800/80 text-gray-700 dark:text-gray-200 shadow-md hover:shadow-xl border-gray-200/50 dark:border-gray-700/50 hover:border-primary-300/70 dark:hover:border-primary-500/50"
          }
        `}
      >
        <div
          className={`absolute inset-0 bg-gradient-to-r from-white/30 via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 ${
            isActive ? "from-white/40" : "from-primary-500/10"
          }`}
        />
        <div className="relative flex items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            {icon && (
              <span className="text-lg filter drop-shadow-sm">{icon}</span>
            )}
            <span className="font-medium">{label}</span>
          </div>
          {isActive && (
            <div className="flex items-center gap-1.5">
              <div className="w-2 h-2 bg-white rounded-full shadow-sm animate-pulse" />
              <svg
                className="w-4 h-4 text-white"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2.5}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
          )}
        </div>
      </button>
    );
  }
);
ToggleButton.displayName = "ToggleButton";

// Filter Modal Content Component
const FilterModalContent = memo(
  ({
    filters,
    onToggle,
    stats,
  }: {
    filters: {
      showStewards: boolean;
      showPoultries: boolean;
      showLiveStocks: boolean;
    };
    onToggle: (key: keyof typeof filters) => void;
    stats: { stewards: number; poultries: number; livestocks: number };
  }) => {
    return (
      <div className="space-y-5 mx-3">
        {/* Modern Stats Cards */}
        <div className="grid grid-cols-3 gap-3 mb-5 pb-5 border-b border-gradient-to-r from-gray-200 via-gray-300 to-gray-200 dark:from-gray-700 dark:via-gray-600 dark:to-gray-700">
          <div className="group relative overflow-hidden rounded-xl bg-gradient-to-br from-primary-50 to-primary-100/50 dark:from-primary-900/30 dark:to-primary-800/20 p-4 text-center border border-primary-200/50 dark:border-primary-700/30 transition-all duration-300 hover:shadow-lg hover:scale-[1.02]">
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
            <div className="relative">
              <div className="text-3xl font-bold bg-gradient-to-r from-primary-600 to-primary-700 dark:from-primary-400 dark:to-primary-300 bg-clip-text text-transparent">
                {stats.stewards + stats.poultries + stats.livestocks}
              </div>
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300 mt-1.5">
                کل موارد
              </div>
            </div>
          </div>
          <div className="group relative overflow-hidden rounded-xl bg-gradient-to-br from-blue-50 to-blue-100/50 dark:from-blue-900/30 dark:to-blue-800/20 p-4 text-center border border-blue-200/50 dark:border-blue-700/30 transition-all duration-300 hover:shadow-lg hover:scale-[1.02]">
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
            <div className="relative">
              <div className="text-3xl font-bold bg-gradient-to-r from-blue-600 to-blue-700 dark:from-blue-400 dark:to-blue-300 bg-clip-text text-transparent">
                {stats.stewards}
              </div>
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300 mt-1.5">
                فروشگاه
              </div>
            </div>
          </div>
          <div className="group relative overflow-hidden rounded-xl bg-gradient-to-br from-green-50 to-green-100/50 dark:from-green-900/30 dark:to-green-800/20 p-4 text-center border border-green-200/50 dark:border-green-700/30 transition-all duration-300 hover:shadow-lg hover:scale-[1.02]">
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
            <div className="relative">
              <div className="text-3xl font-bold bg-gradient-to-r from-green-600 to-green-700 dark:from-green-400 dark:to-green-300 bg-clip-text text-transparent">
                {stats.poultries + stats.livestocks}
              </div>
              <div className="text-xs font-medium text-gray-700 dark:text-gray-300 mt-1.5">
                دام و طیور
              </div>
            </div>
          </div>
        </div>

        <div className="space-y-3">
          <ToggleButton
            label="نمایش فروشگاه‌ها"
            isActive={filters.showStewards}
            onClick={() => onToggle("showStewards")}
            icon="🏪"
          />
          <ToggleButton
            label="نمایش مرغداری‌ها"
            isActive={filters.showPoultries}
            onClick={() => onToggle("showPoultries")}
            icon="🐔"
          />
          <ToggleButton
            label="نمایش دامداری‌ها"
            isActive={filters.showLiveStocks}
            onClick={() => onToggle("showLiveStocks")}
            icon="🐑"
          />
        </div>
      </div>
    );
  }
);
FilterModalContent.displayName = "FilterModalContent";

const MainPage: React.FC = () => {
  const { profile } = useUserProfileStore();
  const { location: currentLocation } = useCurrentLocation();
  const {
    openModal,
    updateModalContent,
    isOpen: isModalOpen,
    title: modalTitle,
  } = useModalStore();
  const mapRef = useRef<any>(null);

  const [filters, setFilters] = useState({
    showStewards: true,
    showPoultries: false,
    showLiveStocks: false,
  });
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [mapBounds, setMapBounds] = useState<{
    north: number;
    south: number;
    east: number;
    west: number;
  } | null>(null);
  const [zoomLevel, setZoomLevel] = useState<number>(14);
  // Use initialViewState for uncontrolled mode - much better performance
  const initialViewState = useMemo(() => {
    const center = getLocationByProvince(profile?.province || "hamedan");
    return {
      longitude: center[1],
      latitude: center[0],
      zoom: 14,
    };
  }, [profile?.province]);

  const { stewardsData, poultryData, livestockData } = useMapData(
    profile?.province,
    filters
  );

  // Helper function to check if a point is within bounds
  const isWithinBounds = useCallback(
    (lat: number, lng: number): boolean => {
      if (!mapBounds) return true; // Show all if bounds not set yet
      return (
        lat >= mapBounds.south &&
        lat <= mapBounds.north &&
        lng >= mapBounds.west &&
        lng <= mapBounds.east
      );
    },
    [mapBounds]
  );

  // Helper function to limit items when zoomed out (deterministic random selection)
  const limitItemsByZoom = useCallback(
    <
      T extends {
        lat?: number;
        lng?: number;
        Lat?: number;
        Long?: number;
        lot?: number;
      }
    >(
      items: T[],
      maxItems: number
    ): T[] => {
      if (items.length <= maxItems) return items;

      // Use deterministic selection based on coordinates for consistency
      // Sort by a hash of coordinates to get consistent "random" selection
      const sorted = [...items].sort((a, b) => {
        const aLat = a.lat || a.Lat || a.lot || 0;
        const aLng = a.lng || a.Long || 0;
        const bLat = b.lat || b.Lat || b.lot || 0;
        const bLng = b.lng || b.Long || 0;

        // Simple hash for deterministic pseudo-randomness
        const aHash = ((aLat * 1000 + aLng) * 17) % 1000;
        const bHash = ((bLat * 1000 + bLng) * 17) % 1000;
        return aHash - bHash;
      });

      return sorted.slice(0, maxItems);
    },
    []
  );

  // Memoized filtered data with search and viewport filtering
  const filteredStewards = useMemo(() => {
    const withCoords =
      stewardsData?.filter(
        (item): item is StewardItem => !!item?.lat && !!item?.lng
      ) || [];

    // If searching, show all search results
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      return withCoords.filter((item) =>
        item?.guilds_name?.toLowerCase().includes(query)
      );
    }

    // If not searching, filter by viewport
    let viewportFiltered = withCoords;
    if (mapBounds) {
      viewportFiltered = withCoords.filter((item) =>
        isWithinBounds(item.lat, item.lng)
      );
    }

    // Limit items when zoomed out (zoom < 10)
    if (zoomLevel < 10) {
      const maxItems = Math.max(20, Math.floor(viewportFiltered.length * 0.1));
      return limitItemsByZoom(viewportFiltered, maxItems);
    }

    return viewportFiltered;
  }, [
    stewardsData,
    searchQuery,
    mapBounds,
    isWithinBounds,
    zoomLevel,
    limitItemsByZoom,
  ]);

  const filteredPoultries = useMemo(() => {
    const withCoords =
      poultryData?.filter(
        (item): item is PoultryItem => !!item?.Lat && !!item?.Long
      ) || [];

    // If searching, show all search results
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      return withCoords.filter((item) =>
        item?.unit_name?.toLowerCase().includes(query)
      );
    }

    // If not searching, filter by viewport
    let viewportFiltered = withCoords;
    if (mapBounds) {
      viewportFiltered = withCoords.filter((item) =>
        isWithinBounds(item.Lat, item.Long)
      );
    }

    // Limit items when zoomed out (zoom < 10)
    if (zoomLevel < 10) {
      const maxItems = Math.max(20, Math.floor(viewportFiltered.length * 0.1));
      return limitItemsByZoom(viewportFiltered, maxItems);
    }

    return viewportFiltered;
  }, [
    poultryData,
    searchQuery,
    mapBounds,
    isWithinBounds,
    zoomLevel,
    limitItemsByZoom,
  ]);

  const filteredLivestocks = useMemo(() => {
    const withCoords =
      livestockData?.filter(
        (item): item is LivestockItem => !!item?.lot && !!item?.lng
      ) || [];

    // If searching, show all search results
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      return withCoords.filter((item) =>
        item?.fullname?.toLowerCase().includes(query)
      );
    }

    // If not searching, filter by viewport
    let viewportFiltered = withCoords;
    if (mapBounds) {
      viewportFiltered = withCoords.filter((item) =>
        isWithinBounds(item.lot, item.lng)
      );
    }

    // Limit items when zoomed out (zoom < 10)
    if (zoomLevel < 10) {
      const maxItems = Math.max(20, Math.floor(viewportFiltered.length * 0.1));
      return limitItemsByZoom(viewportFiltered, maxItems);
    }

    return viewportFiltered;
  }, [
    livestockData,
    searchQuery,
    mapBounds,
    isWithinBounds,
    zoomLevel,
    limitItemsByZoom,
  ]);

  // Search results summary
  const searchResultsCount = useMemo(() => {
    if (!searchQuery.trim()) return 0;
    return (
      (filters.showStewards ? filteredStewards.length : 0) +
      (filters.showPoultries ? filteredPoultries.length : 0) +
      (filters.showLiveStocks ? filteredLivestocks.length : 0)
    );
  }, [
    searchQuery,
    filters,
    filteredStewards.length,
    filteredPoultries.length,
    filteredLivestocks.length,
  ]);

  const handleFilterToggle = useCallback((key: keyof typeof filters) => {
    setFilters((prev) => ({ ...prev, [key]: !prev[key] }));
  }, []);

  const handleOpenFilterModal = useCallback(() => {
    openModal({
      title: "فیلترها",
      content: (
        <FilterModalContent
          filters={filters}
          onToggle={handleFilterToggle}
          stats={{
            stewards: filteredStewards.length,
            poultries: filteredPoultries.length,
            livestocks: filteredLivestocks.length,
          }}
        />
      ),
    });
  }, [
    filters,
    filteredStewards.length,
    filteredPoultries.length,
    filteredLivestocks.length,
    openModal,
    handleFilterToggle,
  ]);

  // Update modal content when filters or stats change (if filter modal is open)
  useEffect(() => {
    if (isModalOpen && modalTitle === "فیلترها") {
      updateModalContent(
        <FilterModalContent
          filters={filters}
          onToggle={handleFilterToggle}
          stats={{
            stewards: filteredStewards.length,
            poultries: filteredPoultries.length,
            livestocks: filteredLivestocks.length,
          }}
        />
      );
    }
  }, [
    isModalOpen,
    modalTitle,
    filters,
    filteredStewards.length,
    filteredPoultries.length,
    filteredLivestocks.length,
    handleFilterToggle,
    updateModalContent,
  ]);

  // Initialize bounds and zoom after map loads and reset when province changes
  useEffect(() => {
    // Reset bounds when province changes
    setMapBounds(null);
    setZoomLevel(14);

    if (mapRef.current) {
      const timer = setTimeout(() => {
        const map = mapRef.current?.getMap();
        if (map) {
          const bounds = map.getBounds();
          const zoom = map.getZoom();
          setMapBounds({
            north: bounds.getNorth(),
            south: bounds.getSouth(),
            east: bounds.getEast(),
            west: bounds.getWest(),
          });
          setZoomLevel(zoom);
        }
      }, 500); // Small delay to ensure map is fully loaded
      return () => clearTimeout(timer);
    }
  }, [profile?.province]);

  const handleLocationClick = useCallback(() => {
    if (currentLocation.length > 0 && mapRef.current) {
      mapRef.current.flyTo({
        center: [currentLocation[1], currentLocation[0]],
        zoom: 16,
        duration: 800,
      });
    }
  }, [currentLocation]);

  const handleProvinceClick = useCallback(() => {
    const center = getLocationByProvince(profile?.province || "hamedan");
    if (center && mapRef.current) {
      mapRef.current.flyTo({
        center: [center[1], center[0]],
        zoom: 14,
        duration: 800,
      });
    }
  }, [profile?.province]);

  const handleStewardMarkerClick = useCallback(
    (item: StewardItem) => {
      const lastSeen =
        formatJustDate(item?.session_last_seen_date) || undefined;
      openModal({
        title: item?.guilds_name || "اطلاعات فروشگاه",
        content: <MainPlaceInfo item={item} userlastseen={lastSeen} />,
        isFullSize: true,
      });
    },
    [openModal]
  );

  if (!profile?.province) {
    return (
      <div className="flex items-center justify-center h-full bg-gradient-to-br from-gray-50 via-white to-gray-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 p-4">
        <div className="text-center space-y-4 animate-fade-in max-w-md">
          <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-gradient-to-br from-primary-500/20 to-primary-600/10">
            <GlobeAltIcon className="w-8 h-8 sm:w-10 sm:h-10 text-primary-600" />
          </div>
          <Typography
            variant="h6"
            className="text-gray-700 dark:text-gray-200 font-semibold text-base sm:text-lg"
          >
            لطفا ابتدا وارد حساب کاربری خود شوید
          </Typography>
          <Typography
            variant="body2"
            className="text-gray-500 dark:text-gray-400 text-sm"
          >
            برای مشاهده نقشه و اطلاعات بازرسی، لطفاً وارد حساب کاربری خود شوید
          </Typography>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full h-[calc(100vh-80px)] relative overflow-hidden bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
      <Map
        ref={mapRef}
        initialViewState={initialViewState}
        key={profile.province}
        reuseMaps={true}
        style={{ width: "100%", height: "100%" }}
        mapStyle={{
          version: 8,
          sources: {
            "osm-tiles": {
              type: "raster",
              tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
              tileSize: 256,
              attribution:
                '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            },
          },
          layers: [
            {
              id: "osm-tiles",
              type: "raster",
              source: "osm-tiles",
              minzoom: 0,
              maxzoom: 22,
            },
          ],
        }}
        dragRotate={false}
        touchZoomRotate={false}
        doubleClickZoom={true}
        scrollZoom={true}
        minZoom={3}
        maxZoom={18}
        dragPan={true}
        touchPitch={false}
        renderWorldCopies={false}
        onMoveEnd={() => {
          if (mapRef.current) {
            const map = mapRef.current.getMap();
            if (map) {
              const bounds = map.getBounds();
              const zoom = map.getZoom();
              setMapBounds({
                north: bounds.getNorth(),
                south: bounds.getSouth(),
                east: bounds.getEast(),
                west: bounds.getWest(),
              });
              setZoomLevel(zoom);
            }
          }
        }}
      >
        {filters.showStewards &&
          filteredStewards.map((item) => (
            <StewardMarker
              key={`steward-${item.lat}-${item.lng}`}
              item={item}
              onMarkerClick={handleStewardMarkerClick}
            />
          ))}

        {filters.showPoultries &&
          filteredPoultries.map((item) => (
            <PoultryMarker
              key={`poultry-${item.Lat}-${item.Long}`}
              item={item}
            />
          ))}

        {filters.showLiveStocks &&
          filteredLivestocks.map((item) => (
            <LivestockMarker
              key={`livestock-${item.lot}-${item.lng}`}
              item={item}
            />
          ))}

        {currentLocation.length > 0 && (
          <CurrentLocationMarker
            location={currentLocation as [number, number]}
            inspectorName={profile?.fullname}
          />
        )}
      </Map>

      <LocationButton
        currentLocation={currentLocation}
        onLocationClick={handleLocationClick}
      />
      <ProvinceButton onProvinceClick={handleProvinceClick} />

      {/* Search Bar */}
      <div className="absolute top-3 right-3 sm:top-4 sm:right-4 z-[100] w-[calc(100%-120px)] sm:w-80 max-w-md">
        <div className="relative">
          <div
            className={`group relative bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl shadow-lg border rounded-xl transition-all duration-300 ${
              isSearchFocused
                ? "border-primary-400 shadow-xl ring-2 ring-primary-500/20"
                : "border-white/30 dark:border-gray-700/30 hover:border-primary-300/50"
            }`}
          >
            <div className="flex items-center gap-2 px-3 py-2.5">
              <MagnifyingGlassIcon className="w-5 h-5 text-gray-400 dark:text-gray-500 flex-shrink-0" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => setIsSearchFocused(true)}
                onBlur={() => setIsSearchFocused(false)}
                placeholder="جستجو در نقشه..."
                className="flex-1 bg-transparent border-none outline-none text-sm text-gray-700 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 font-medium"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                  aria-label="پاک کردن"
                >
                  <XMarkIcon className="w-4 h-4 text-gray-400 dark:text-gray-500" />
                </button>
              )}
            </div>
          </div>
          {searchQuery && searchResultsCount > 0 && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl rounded-xl shadow-xl border border-white/30 dark:border-gray-700/30 p-2 animate-fade-in">
              <div className="text-xs text-gray-600 dark:text-gray-400 px-2 py-1">
                {searchResultsCount} نتیجه پیدا شد
              </div>
            </div>
          )}
          {searchQuery && searchResultsCount === 0 && (
            <div className="absolute top-full left-0 right-0 mt-2 bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl rounded-xl shadow-xl border border-white/30 dark:border-gray-700/30 p-3 animate-fade-in">
              <div className="text-xs text-gray-500 dark:text-gray-400 text-center">
                نتیجه‌ای یافت نشد
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Filter Button */}
      <div className="absolute top-3 left-3 sm:top-4 sm:left-4 z-[100]">
        <button
          onClick={handleOpenFilterModal}
          className="group relative bg-gradient-to-br from-white/95 to-white/85 dark:from-gray-800/95 dark:to-gray-800/85 backdrop-blur-xl shadow-lg hover:shadow-xl border border-white/20 dark:border-gray-700/30 rounded-xl p-2.5 sm:p-3 transition-all duration-300 hover:scale-105 active:scale-95"
          aria-label="فیلترها"
        >
          <div className="absolute inset-0 bg-gradient-to-br from-primary-500/10 to-primary-600/5 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          <FunnelIcon className="relative w-5 h-5 sm:w-6 sm:h-6 text-primary-600 dark:text-primary-400 group-hover:text-primary-700 dark:group-hover:text-primary-300 transition-colors duration-300" />
          {(filters.showStewards ||
            filters.showPoultries ||
            filters.showLiveStocks) && (
            <div className="absolute -top-1 -right-1 w-4 h-4 bg-primary-500 rounded-full border-2 border-white dark:border-gray-800 flex items-center justify-center">
              <span className="text-[10px] text-white font-bold">
                {(filters.showStewards ? 1 : 0) +
                  (filters.showPoultries ? 1 : 0) +
                  (filters.showLiveStocks ? 1 : 0)}
              </span>
            </div>
          )}
        </button>
      </div>
    </div>
  );
};

export default MainPage;
