import { getShipIcon } from "@/services/map_service";
import React from "react";
import { Animated, Image, StyleSheet, View } from "react-native";
import { Marker } from "react-native-maps";

interface MarkerCustomProps {
  id: string;
  latitude: number;
  longitude: number;
  shipName?: string;
  description?: string;
  stateLevel?: number;
  isFishing?: boolean;
  heading?: number;
  zIndex?: number;
  anchor?: { x: number; y: number };
  tracksViewChanges?: boolean;
  identifier?: string;
  animated?: {
    scale: Animated.Value;
    opacity: Animated.Value;
  };
}

export const MarkerCustom: React.FC<MarkerCustomProps> = ({
  id,
  latitude,
  longitude,
  shipName,
  description,
  stateLevel = 0,
  isFishing = false,
  heading = 0,
  zIndex = 50,
  anchor = { x: 0.5, y: 0.5 },
  tracksViewChanges = false,
  identifier,
  animated,
}) => {
  const uniqueKey =
    id || `marker-${latitude.toFixed(6)}-${longitude.toFixed(6)}`;

  return (
    <Marker
      key={uniqueKey}
      coordinate={{
        latitude,
        longitude,
      }}
      zIndex={zIndex}
      anchor={anchor}
      title={shipName}
      description={description}
      tracksViewChanges={tracksViewChanges}
      identifier={identifier || uniqueKey}
    >
      <View className="w-8 h-8 items-center justify-center">
        <View style={styles.pingContainer}>
          {animated && stateLevel === 3 && (
            <Animated.View
              style={[
                styles.pingCircle,
                {
                  transform: [{ scale: animated.scale }],
                  opacity: animated.opacity,
                },
              ]}
            />
          )}
          <Image
            source={(() => {
              const icon = getShipIcon(stateLevel, isFishing);
              return typeof icon === "string" ? { uri: icon } : icon;
            })()}
            style={{
              width: 32,
              height: 32,
              transform: [
                {
                  rotate: `${
                    typeof heading === "number" && !isNaN(heading) ? heading : 0
                  }deg`,
                },
              ],
            }}
          />
        </View>
      </View>
    </Marker>
  );
};

export default MarkerCustom;

const styles = StyleSheet.create({
  pingContainer: {
    width: 32,
    height: 32,
    alignItems: "center",
    justifyContent: "center",
    overflow: "visible",
  },
  pingCircle: {
    position: "absolute",
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "#ED3F27",
  },
});
