import { Marker, Popup, Tooltip, Polyline } from 'react-leaflet';
import L from 'leaflet';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import type { LiveVolunteer } from '@/types/tracking';

dayjs.extend(relativeTime);

// Color palette for distinguishing volunteers
const COLORS = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c', '#e67e22', '#e91e63'];

function getColor(index: number) {
  return COLORS[index % COLORS.length]!;
}

function createVolunteerIcon(color: string) {
  return L.divIcon({
    className: '',
    iconSize: [20, 20],
    iconAnchor: [10, 10],
    html: `
      <div style="
        width: 16px; height: 16px;
        background: ${color};
        border: 2px solid #fff;
        border-radius: 50%;
        box-shadow: 0 0 6px ${color}80;
        animation: pulse 2s ease-in-out infinite;
      "></div>
      <style>
        @keyframes pulse {
          0%, 100% { box-shadow: 0 0 6px ${color}80; }
          50% { box-shadow: 0 0 14px ${color}cc; }
        }
      </style>
    `,
  });
}

interface VolunteerMarkerProps {
  volunteer: LiveVolunteer;
  index: number;
}

export default function VolunteerMarker({ volunteer, index }: VolunteerMarkerProps) {
  const color = getColor(index);
  const position: [number, number] = [volunteer.latitude, volunteer.longitude];
  const name = volunteer.name || volunteer.email.split('@')[0]!;
  const distanceText = volunteer.recentTrail.length > 1
    ? `${volunteer.recentTrail.length} recent points`
    : '';

  return (
    <>
      {/* Recent trail polyline */}
      {volunteer.recentTrail.length > 1 && (
        <Polyline
          positions={volunteer.recentTrail}
          pathOptions={{
            color,
            weight: 2,
            opacity: 0.6,
            dashArray: '6 4',
          }}
        />
      )}

      {/* Volunteer position marker */}
      <Marker position={position} icon={createVolunteerIcon(color)}>
        <Tooltip permanent direction="top" offset={[0, -12]}>
          <span style={{ fontSize: 11, fontWeight: 600 }}>{name}</span>
        </Tooltip>
        <Popup>
          <div style={{ minWidth: 160 }}>
            <div style={{ fontWeight: 600, marginBottom: 4 }}>{name}</div>
            <div style={{ fontSize: 12, color: '#888' }}>{volunteer.email}</div>
            <div style={{ fontSize: 12, marginTop: 6 }}>
              Last update: {dayjs(volunteer.lastRecordedAt).fromNow()}
            </div>
            {distanceText && (
              <div style={{ fontSize: 12 }}>{distanceText}</div>
            )}
            {volunteer.canvassSessionId && (
              <div style={{ fontSize: 12, marginTop: 4, color: '#2ecc71' }}>
                In canvass session
              </div>
            )}
          </div>
        </Popup>
      </Marker>
    </>
  );
}
