import { useRef } from 'react'
import { Marker, Popup } from 'react-leaflet'
import { useTranslation } from 'react-i18next'
import { wpStartIcon, wpMidIcon, wpFinishIcon } from './mapIcons'
import { PURPOSES } from './types'
import type { FlightPoint, MovingPointInfo } from './types'
import type L from 'leaflet'

interface Props {
  point: FlightPoint
  points: FlightPoint[]
  index: number
  mapElement: HTMLElement | null
  onDrag: (index: number, position: { lat: number; lng: number }) => void
  onDragEnd: (index: number, position: { lat: number; lng: number }) => void
  onAltitudeChange: (index: number, altitude: number) => void
  onMetaChange: (index: number, meta: string[]) => void
  onRemove: (id: string) => void
  onMoving: (info: MovingPointInfo | null) => void
}

export default function MapPoint({
  point, points, index, mapElement,
  onDrag, onDragEnd, onAltitudeChange, onMetaChange, onRemove, onMoving,
}: Props) {
  const { t } = useTranslation()
  const markerRef = useRef<L.Marker>(null)

  const icon = index === 0 ? wpStartIcon : index === points.length - 1 ? wpFinishIcon : wpMidIcon

  const handleMove = (e: L.LeafletEvent) => {
    const marker = markerRef.current
    if (!marker || !mapElement) return
    const markerEl = (marker as unknown as { _icon: HTMLElement })._icon
    if (!markerEl) return
    const mapRect = mapElement.getBoundingClientRect()
    const mRect = markerEl.getBoundingClientRect()
    const dx = mRect.left - mapRect.left + mRect.width > mapRect.width / 2 ? -150 : 200
    const dy = mRect.top + mRect.height > mapRect.height / 2 ? -150 : 150
    onMoving({ x: mRect.left - mapRect.left + dx, y: mRect.top - mapRect.top + dy, latlng: (e.target as L.Marker).getLatLng() })
  }

  const toggleMeta = (value: string) => {
    const newMeta = point.meta.includes(value) ? point.meta.filter(m => m !== value) : [...point.meta, value]
    onMetaChange(index, newMeta)
  }

  return (
    <Marker
      position={point.position}
      icon={icon}
      draggable
      ref={markerRef}
      eventHandlers={{
        drag: (e) => onDrag(index, (e.target as L.Marker).getLatLng()),
        dragend: (e) => { onDragEnd(index, (e.target as L.Marker).getLatLng()); onMoving(null) },
        move: handleMove,
      }}
    >
      <Popup>
        <div style={{ minWidth: 148, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div
            className="mono"
            style={{ color: 'var(--accent-amber)', fontSize: 12, fontWeight: 600 }}
          >
            {t('flights.planner.point')} {index + 1}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <label style={{ color: 'var(--text-secondary)', fontSize: 11 }}>
              {t('flights.planner.altitude')}
            </label>
            <input
              type="range"
              min={0}
              max={3000}
              value={point.altitude}
              onChange={e => onAltitudeChange(index, Number(e.target.value))}
              className="w-full"
              style={{ accentColor: 'var(--accent-amber)' }}
            />
            <span
              className="mono"
              style={{ color: 'var(--text-primary)', fontSize: 11 }}
            >
              {point.altitude}m
            </span>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {PURPOSES.map(p => (
              <label
                key={p.value}
                style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer', color: 'var(--text-primary)', fontSize: 12 }}
              >
                <input
                  type="checkbox"
                  checked={point.meta.includes(p.value)}
                  onChange={() => toggleMeta(p.value)}
                  style={{ accentColor: 'var(--accent-amber)' }}
                />
                {t(`flights.planner.${p.label}`)}
              </label>
            ))}
          </div>
          <button
            onClick={() => onRemove(point.id)}
            style={{ color: 'var(--accent-red)', fontSize: 11, background: 'none', border: 'none', padding: 0, cursor: 'pointer', textAlign: 'left', textDecoration: 'none' }}
            onMouseOver={e => (e.currentTarget.style.textDecoration = 'underline')}
            onMouseOut={e => (e.currentTarget.style.textDecoration = 'none')}
          >
            {t('flights.planner.removePoint')}
          </button>
        </div>
      </Popup>
    </Marker>
  )
}
