// MapSift component (Map.tsx)
"use client";
import "leaflet/dist/leaflet.css";
import "react-leaflet-markercluster/styles";
import L from "leaflet";
import React, { useEffect, useRef, useMemo } from "react";
import dynamic from "next/dynamic";
import MarkerClusterGroup from "react-leaflet-markercluster";
import { format, isSameDay } from "date-fns";
import "./Map.css";
import PriceListContent from "./PriceListContent";
import { useAppDispatch, useAppSelector } from "../../../hooks/useDispatch";
import { updateCampaignFormAlt } from "../../../redux/features/main/campaigns/advertAction";
import {
  normalizePrice,
  calculateStartDateFromDays,
} from "@/app/utils/datehelpers";
const MapContainer = dynamic(
  () => import("react-leaflet").then((mod) => mod.MapContainer),
  { ssr: false }
);
const TileLayer = dynamic(
  () => import("react-leaflet").then((mod) => mod.TileLayer),
  { ssr: false }
);
const Marker = dynamic(
  () => import("react-leaflet").then((mod) => mod.Marker),
  { ssr: false }
);
const Popup = dynamic(() => import("react-leaflet").then((mod) => mod.Popup), {
  ssr: false,
});

interface IconDefaultPrototype {
  _getIconUrl?: () => string;
}

// Fix for default marker icons
delete (L.Icon.Default.prototype as IconDefaultPrototype)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png",
  iconUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
});

// Define the event interface
interface Event {
  id: number;
  title: string;
  description: string;
  description_en: string;
  cover_image: string;
  start_date: string;
  end_date: string;
  time: string;
  end_time: string;
  city_name: string | null;
  postal_code: string;
  latitude: string;
  longitude: string;
  slug: string;
  cost: number;
  distance: number;
  event_count: number;
  event_category_id: string;
  pricing:any
}

interface LeafletMapProps {
  events: any[];
  defaultCenter?: L.LatLngExpression;
  defaultZoom?: number
}

const containerStyle: React.CSSProperties = {
  width: "100%", // Changed from 2400px to 100% for responsiveness
  height: "82vh",
};

// Create a custom icon for markers

const formatTime = (timeString: string) => {
  if (!timeString) return "";
  const [hours, minutes] = timeString.split(":");
  return minutes === "00"
    ? `${parseInt(hours, 10)}h`
    : `${parseInt(hours, 10)}h${minutes}`;
};

const formatEventTime = (
  startDate: string,
  startTime: string = "00:00",
  endDate: string,
  endTime: string = "00:00"
): React.ReactNode => {
  if (!startDate || !endDate) return "Schedule unavailable";

  try {
    const parseSafe = (dateStr: string, timeStr: string): Date => {
      const [year, month, day] = dateStr.split("-").map(Number);
      const [hours = 0, minutes = 0] = timeStr.includes(":")
        ? timeStr.split(":").map(Number)
        : [0, 0];
      return new Date(year, month - 1, day, hours, minutes);
    };

    let start = parseSafe(startDate, startTime);
    let end = parseSafe(endDate, endTime);

    if (start > end) {
      [start, end] = [end, start];
      [startDate, endDate] = [endDate, startDate];
      [startTime, endTime] = [endTime, startTime];
    }

    const now = new Date();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);

    let dateLabel = "";
    if (start <= now && now <= end) {
      dateLabel = "Today";
    } else if (start.toDateString() === today.toDateString()) {
      dateLabel = "Today";
    } else if (start.toDateString() === tomorrow.toDateString()) {
      dateLabel = "Tomorrow";
    }

    const formatCompactDate = (dateStr: string) => {
      const date = parseSafe(dateStr, "00:00");
      return format(date, "d MMM").replace(".", "");
    };

    const formatTimeDisplay = (timeStr: string) => {
      return formatTime(timeStr);
    };

    if (!isSameDay(start, end)) {
      return (
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            lineHeight: "1.1",
          }}
        >
          <div>
            {dateLabel ? (
              <span>
                {dateLabel}, {formatTimeDisplay(startTime)}
              </span>
            ) : (
              <span>
                {formatCompactDate(startDate)}, {formatTimeDisplay(startTime)}
              </span>
            )}
          </div>
          <div style={{ marginTop: "2px" }}>
            - {formatCompactDate(endDate)}, {formatTimeDisplay(endTime)}
          </div>
        </div>
      );
    }

    return (
      <div
        style={{ display: "flex", flexDirection: "column", lineHeight: "1.1" }}
      >
        <div>{dateLabel || formatCompactDate(startDate)}</div>
        <div>
          {formatTimeDisplay(startTime)} - {formatTimeDisplay(endTime)}
        </div>
      </div>
    );
  } catch {
    return `Schedule information unavailable`;
  }
};
const createCustomIcon = (event: Event, isSelected: boolean) => {
  const opacity = isSelected ? 0.5 : 1;
  const cursorStyle = isSelected ? "default" : "pointer";

  if (event?.cover_image) {
    const size = 65;
    return L.divIcon({
      html: ` 
          <div style="position: relative; display: flex; flex-direction: column; align-items: center; cursor: ${cursorStyle};">
            <div style="
              width: ${size}px;
              height: ${size}px;
              border-radius: 50%;
              background: white;
              border: 1px solid #000;
              display: flex;
              align-items: center;
              justify-content: center;
              overflow: hidden;
              box-shadow: 0 2px 4px rgba(0,0,0,0.2);
              z-index: 1;
              opacity: ${opacity};
              filter: ${isSelected ? "grayscale(50%)" : "none"};
            ">
              <img src="https://admin.eventx.fr/uploads/events/${
                event.cover_image
              }" 
                   style="width: ${size - 2}px; height: ${
        size - 2
      }px; object-fit: cover;"
                   alt="${event?.title || "Event image"}"
                   onerror="this.style.display='none'"
                   class="marker-image"
              />
            </div>
            <div style="
              width: 0;
              height: 0;
              border-left: 10px solid transparent;
              border-right: 10px solid transparent;
              border-top: 15px solid #000;
              margin-top: -5px;
              opacity: ${opacity};
            "></div>
          </div>
        `,
      iconSize: [size, size + 15],
      iconAnchor: [size / 2, (size + 15) / 2],
      popupAnchor: [0, -(size + 15) / 2],
      className: `custom-marker-icon ${isSelected ? "selected-event" : ""}`,
    });
  } else {
    return L.divIcon({
      html: `
          <div style="
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: white;
            border: 2px solid #000;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
            opacity: ${opacity};
            filter: ${isSelected ? "grayscale(50%)" : "none"};
            cursor: ${cursorStyle};
          ">
            <img src="/logo.png" style="width: 24px; height: 24px; object-fit: contain;"/>
          </div>
        `,
      iconSize: [30, 30],
      iconAnchor: [15, 15],
      popupAnchor: [0, -15],
      className: `default-marker-icon ${isSelected ? "selected-event" : ""}`,
    });
  }
};
const MapSift: React.FC<LeafletMapProps> = ({
  events = [],
  defaultCenter = [46.603354, 1.888334] as any,
  defaultZoom = 6
}) => {
  const priceListVisibleRef = useRef<{ [key: number]: boolean }>({});
  const animationTriggeredRef = useRef<{ [key: number]: boolean }>({});
    const mapRef = useRef<L.Map | null>(null);
  const { selectedEvents,campaignForm,geoPricingDataArray} = useAppSelector((state) => state.compaign);
   const dynamicCenter = useMemo((): any => {
    if (campaignForm.mapCenterlat !=="" && campaignForm.mapCenterlang !=="") {
      const lat = parseFloat(campaignForm.mapCenterlat);
      const lng = parseFloat(campaignForm.mapCenterlang);
      if (!isNaN(lat) && !isNaN(lng) && 
          lat >= -90 && lat <= 90 && 
          lng >= -180 && lng <= 180) {
        return [lat, lng] as L.LatLngTuple;
      }
    }
    else{
      return defaultCenter;

    }
  }, [campaignForm.mapCenterlat, campaignForm.mapCenterlang, defaultCenter]);
    const dynamicZoom = useMemo(() => {
    return (campaignForm.mapCenterlat !== "" && campaignForm.mapCenterlang !== "") ? 10 : defaultZoom;
  }, [campaignForm.mapCenterlat, campaignForm.mapCenterlang, defaultZoom]);

  // Fly to new location when coordinates change
  useEffect(() => {
    if (mapRef.current && campaignForm.mapCenterlat !== "" && campaignForm.mapCenterlang !== "") {
      const lat = parseFloat(campaignForm.mapCenterlat);
      const lng = parseFloat(campaignForm.mapCenterlang);
      
      if (!isNaN(lat) && !isNaN(lng) && 
          lat >= -90 && lat <= 90 && 
          lng >= -180 && lng <= 180) {
        
        // Fly to the new location with smooth animation
        mapRef.current.flyTo([lat, lng], dynamicZoom, {
          duration: 1.5, // Animation duration in seconds
          easeLinearity: 0.25
        });
      }
    }
  }, [campaignForm.mapCenterlat, campaignForm.mapCenterlang, dynamicZoom]);
  const isEventSelected = useMemo(() => {
    const selectedEventIds = selectedEvents.map((event) =>
      typeof event.event_id === "string"
        ? parseInt(event.event_id)
        : event.event_id
    );
    return (eventId: number) => selectedEventIds.includes(eventId);
  }, [selectedEvents]);
  const dispatch = useAppDispatch();
  const handleViewEvent = (event: Event) => {
    window.open(
      `https://eventx.fr/events/${event.city_name}/${event?.slug}`,
      "_blank"
    );
  };
  const handleEventClick = (
    event: Event,
    price: number,
    selectedDay: number
  ) => {
    if (isEventSelected(event.id)) {
      return;
    }
    dispatch(
      updateCampaignFormAlt({
        key: "title",
        value: event.title || "",
      })
    );
    if (event.start_date) {
      dispatch(
        updateCampaignFormAlt({
          key: "startDate",
          value: event.start_date,
        })
      );
    }
    if (event.cover_image) {
      dispatch(
        updateCampaignFormAlt({
          key: "eventImageUrl",
          value: `https://admin.eventx.fr/uploads/events/${event.cover_image}`,
        })
      );
    }
    if (event.id) {
      dispatch(
        updateCampaignFormAlt({
          key: "event_id",
          value: event.id,
        })
      );
    }
    if (event.end_date) {
      const calculatedStartDate = calculateStartDateFromDays(
        event.end_date,
        selectedDay
      );

      dispatch(
        updateCampaignFormAlt({
          key: "startDate",
          value: calculatedStartDate || "",
        })
      );

      dispatch(
        updateCampaignFormAlt({
          key: "endDate",
          value: event.end_date,
        })
      );
    }
    if (event.city_name) {
      dispatch(
        updateCampaignFormAlt({
          key: "location",
          value: event.city_name,
        })
      );

      dispatch(
        updateCampaignFormAlt({
          key: "commune",
          value: event.city_name,
        })
      );
    }
    if (event.postal_code) {
      dispatch(
        updateCampaignFormAlt({
          key: "postcode",
          value: event.postal_code,
        })
      );
    }
    dispatch(
      updateCampaignFormAlt({
        key: "price",
        value: normalizePrice(price),
      })
    );
    dispatch(
      updateCampaignFormAlt({
        key: "tier",
        value: event.pricing.tier,
      })
    );
     dispatch(
      updateCampaignFormAlt({
        key: "geo_price_level",
        value: event.pricing.tier,
      })
    );
    let pricePerDay = ""; 
  
  if (campaignForm.advert_type === "large") {
    // For large advert_type, use specific media type pricing
    switch (campaignForm.media_type) {
      case "image":
        pricePerDay = event.pricing.large_image ;
        break;
      case "rich text":
        pricePerDay = event.pricing.banner ;
        break;
      case "video":
        pricePerDay = event.pricing.large_image_video ;
        break;
      default:
        pricePerDay = event.pricing.large_image ;
    }
  } else if (campaignForm.advert_type === "medium") {
  // For medium advert_type
  switch (campaignForm.media_type) {
    case "image":
      pricePerDay = event.pricing.image;
      break;
    default:
      pricePerDay = event.pricing.image;
  }
}
else if (campaignForm.advert_type === "pop under") {
  switch (campaignForm.media_type) {
    case "image":
      pricePerDay = event.pricing.large_image_rich_text;
      break;
    default:
      pricePerDay = event.pricing.large_image_rich_text;
  }
}

  dispatch(
    updateCampaignFormAlt({
      key: "price_per_day",
      value: pricePerDay,
    })
  );
    dispatch(
      updateCampaignFormAlt({
        key: "duration",
        value: selectedDay,
      })
    );
  };
  const triggerAnimations = (eventId: number) => {
    if (animationTriggeredRef.current[eventId]) return;

    animationTriggeredRef.current[eventId] = true;

    // Use setTimeout to ensure DOM is ready
    setTimeout(() => {
      const popupElement = document.querySelector(
        `[data-event-id="${eventId}"] .leaflet-popup-content`
      ) as HTMLElement;
      if (popupElement) {
        const availabilityContainer = popupElement.querySelector(
          ".availability-container"
        );
        const priceContent = popupElement.querySelector(
          ".price-popup-content:not(.hidden)"
        );

        if (availabilityContainer) {
          availabilityContainer.classList.add("animate-in");
        }

        if (priceContent) {
          priceContent.classList.add("animate-in");
        }
      }
    }, 100);
  };
  const handlePriceListClick = (eventId: number, popupElement: HTMLElement) => {
    const isVisible = priceListVisibleRef.current[eventId] || false;
    priceListVisibleRef.current[eventId] = !isVisible;

    const mainContent = popupElement.querySelector(".main-popup-content");
    const priceContent = popupElement.querySelector(".price-popup-content");
    const priceListContainer = popupElement.querySelector(
      ".price-list-container"
    );
    const popupWrapper = popupElement.closest(".leaflet-popup-content-wrapper");
    if (mainContent && priceContent && priceListContainer && popupWrapper) {
      if (isVisible) {
        // Show main content, hide price content
        mainContent.classList.remove("hidden");
        priceContent.classList.add("hidden");
        popupWrapper.classList.remove("price-popup-active");
      } else {
        // Hide main content, show price content
        mainContent.classList.add("hidden");
        priceContent.classList.remove("hidden");
        priceListContainer.classList.add("hidden");
        popupWrapper.classList.add("price-popup-active");
      }
    }
  };

  const handleBackClick = (eventId: number, popupElement: HTMLElement) => {
    priceListVisibleRef.current[eventId] = false;

    const mainContent = popupElement.querySelector(".main-popup-content");
    const priceContent = popupElement.querySelector(".price-popup-content");
    const priceListContainer = popupElement.querySelector(
      ".price-list-container"
    );
    const popupWrapper = popupElement.closest(".leaflet-popup-content-wrapper");
    if (mainContent && priceContent && priceListContainer && popupWrapper) {
      mainContent.classList.remove("hidden");
      priceContent.classList.add("hidden");
      priceListContainer.classList.remove("hidden");
      popupWrapper.classList.remove("price-popup-active");
    }
  };

  const validEvents = useMemo(() => {
    return events.filter((event) => {
      const lat = parseFloat(event.latitude);
      const lng = parseFloat(event.longitude);
      return !isNaN(lat) && !isNaN(lng);
    });
  }, [events]);
  useEffect(() => {
    animationTriggeredRef.current = {};
  }, [events]);
 const getPriceForEvent = (event: Event): any => {
 const eventTier = event.pricing?.tier;
const pricingObject = geoPricingDataArray.find(item => item.tier === eventTier);
if (campaignForm.advert_type === "large") {
  switch (campaignForm.media_type) {
    case "image":
      return (pricingObject.large_image || "").replace('.', ',');
    case "rich text":
      return (pricingObject.banner || "").replace('.', ',');
    case "video":
      return (pricingObject.large_image_video || "").replace('.', ',');
    default:
      return (pricingObject.large_image || "").replace('.', ',');
  }
} else if (campaignForm.advert_type === "medium") {
  return (pricingObject.image || "").replace('.', ',');
} else if (campaignForm.advert_type === "pop under") {
  return (pricingObject.large_image_rich_text || "").replace('.', ',');
}
};

  return (
    <div style={containerStyle}>
      <MapContainer
        center={dynamicCenter}
         zoom={dynamicZoom}
        style={containerStyle}
        scrollWheelZoom={true}
        maxZoom={19}
         ref={mapRef}
      >
        <TileLayer
          url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/">CARTO</a>'
        />

        <MarkerClusterGroup>
          {validEvents.map((event) => {
            const lat = parseFloat(event.latitude);
            const lng = parseFloat(event.longitude);
            const isSelected = isEventSelected(event.id);
            const eventPrice = getPriceForEvent(event);
            return (
              <Marker
                key={event.id}
                position={[lat, lng] as L.LatLngTuple}
                icon={createCustomIcon(event, isSelected)}
                interactive={!isSelected}
                eventHandlers={{
                  popupopen: () => {
                    setTimeout(() => {
                      triggerAnimations(event.id);
                    }, 300);
                  },
                  popupclose: () => {
                    animationTriggeredRef.current[event.id] = false;

                    // Remove animation classes
                    const popupElement = document.querySelector(
                      `[data-event-id="${event.id}"] .leaflet-popup-content`
                    ) as HTMLElement;
                    if (popupElement) {
                      const availabilityContainer = popupElement.querySelector(
                        ".availability-container"
                      );
                      const priceContent = popupElement.querySelector(
                        ".price-popup-content"
                      );

                      if (availabilityContainer) {
                        availabilityContainer.classList.remove("animate-in");
                      }
                      if (priceContent) {
                        priceContent.classList.remove("animate-in");
                      }
                    }
                  },
                }}
              >
                {!isSelected && (
                  <Popup
                    className="popup-containerNew"
                    offset={[0, 13]}
                    closeButton={false}
                  >
                    <div className="tooltip-container">
                      {/* Main Content */}
                      <div className="main-popup-content">
                        <header className="tooltip-header">
                          <p>{event?.title}</p>
                        </header>

                        <div className="tooltip-content">
                          {event?.cover_image && (
                            <div
                              className="tooltip-image"
                              style={{
                                backgroundImage: `url(https://admin.eventx.fr/uploads/events/${event?.cover_image})`,
                              }}
                            />
                          )}

                          {event?.description && (
                            <p
                              className="tooltip-description"
                              dangerouslySetInnerHTML={{
                                __html: event.description.replace(
                                  /<[^>]*>?/gm,
                                  ""
                                ),
                              }}
                            />
                          )}

                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "flex-end",
                              marginTop: "10px",
                            }}
                          >
                            <button className="tooltip-time-button">
                              {formatEventTime(
                                event?.start_date,
                                event?.time,
                                event?.end_date,
                                event?.end_time
                              )}
                            </button>

                            <div
                              style={{
                                display: "flex",
                                flexDirection: "column",
                                gap: "0px",
                              }}
                            >
                              <button className="tooltip-view-button1">
                                <span style={{ marginTop: "2px" }}>
                                  {event?.id}
                                </span>
                              </button>
                              <button
                                className="tooltip-view-button hover-button"
                                onClick={() => handleViewEvent(event)}
                                style={{
                                  borderRadius: "12px 0 0 12px",
                                  alignSelf: "flex-end",
                                }}
                              >
                                <span
                                  style={{
                                    marginTop: "0px",
                                    fontFamily: "Acumin Pro Condensed SemiBold",
                                  }}
                                >
                                  View
                                </span>
                              </button>
                            </div>
                          </div>

                          <div
                            style={{
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                              textAlign: "center",
                              fontFamily: "Acumin Pro Semi Bold",
                              color: "#000000",
                              fontSize: "17px",
                              marginTop: "20px",
                              marginBottom: "-15px",
                            }}
                          >
                            {event?.city_name}, {event?.postal_code}
                          </div>
                        </div>
                        <div className="availability-container">
                          <div className="availability-text">
                            AVAILABLE <br />
                            (TIER {event.pricing.tier})
                          </div>
                          <div className="availability-price">
                            <span className="price-value">{eventPrice}€</span>
                            <span className="price-unit">/day</span>
                          </div>
                        </div>
                      </div>

                      <div className="price-popup-content hidden">
                        <PriceListContent
                          event={event}
                          handleEventClick={handleEventClick}
                          onBack={() => {
                            const popupElement = document.querySelector(
                              ".leaflet-popup-content"
                            ) as HTMLElement;
                            if (popupElement) {
                              handleBackClick(event.id, popupElement);
                            }
                          }}
                        />
                      </div>
                    </div>

                    <div
                      className="price-list-container"
                      onClick={(e) => {
                        const popupElement = (e.target as HTMLElement).closest(
                          ".leaflet-popup-content"
                        ) as HTMLElement;
                        if (popupElement) {
                          handlePriceListClick(event.id, popupElement);
                        }
                      }}
                    >
                      <span className="price-list-text">PRICE LIST</span>
                      <img
                        src="/view_popup.svg"
                        alt="view popup icon"
                        className="price-list-icon"
                      />
                    </div>
                  </Popup>
                )}
              </Marker>
            );
          })}
        </MarkerClusterGroup>
      </MapContainer>
    </div>
  );
};

export default MapSift;
