'use client';

import { useState, useEffect, useCallback } from 'react';
import dynamic from 'next/dynamic';
import type { Participant, MapViewport, Waypoint, ParticipantLocation } from '@/types';
import { isInC3NavArea } from '@/lib/c3nav';
import { useRoomStore } from '@/stores/room';
import NavigationPanel from './NavigationPanel';

// Dynamic imports to avoid SSR issues
const MapView = dynamic(() => import('./MapView'), {
  ssr: false,
  loading: () => <MapLoading />,
});

const C3NavEmbed = dynamic(() => import('./C3NavEmbed'), {
  ssr: false,
  loading: () => <MapLoading />,
});

function MapLoading() {
  return (
    <div className="w-full h-full bg-rmaps-dark flex items-center justify-center">
      <div className="text-white/60">Loading map...</div>
    </div>
  );
}

type MapMode = 'outdoor' | 'indoor' | 'auto';

interface DualMapViewProps {
  participants: Participant[];
  waypoints?: Waypoint[];
  currentUserId?: string;
  currentLocation?: ParticipantLocation | null;
  eventId?: string;
  initialMode?: MapMode;
  onParticipantClick?: (participant: Participant) => void;
  onWaypointClick?: (waypoint: Waypoint) => void;
  onIndoorPositionSet?: (position: { level: number; x: number; y: number }) => void;
  /** Whether location sharing is active */
  isSharing?: boolean;
  /** Callback to toggle location sharing */
  onToggleSharing?: () => void;
  /** Location to zoom/fly to */
  zoomToLocation?: { latitude: number; longitude: number } | null;
  /** Selected participant (for navigation panel) */
  selectedParticipant?: Participant | null;
  /** Callback when selected participant changes */
  onSelectedParticipantChange?: (participant: Participant | null) => void;
}

// CCC venue bounds (Hamburg Congress Center)
const CCC_BOUNDS = {
  north: 53.558,
  south: 53.552,
  east: 9.995,
  west: 9.985,
};

export default function DualMapView({
  participants,
  waypoints = [],
  currentUserId,
  currentLocation,
  eventId = '39c3',
  initialMode = 'auto',
  onParticipantClick,
  onWaypointClick,
  onIndoorPositionSet,
  isSharing = false,
  onToggleSharing,
  zoomToLocation,
  selectedParticipant: selectedParticipantProp,
  onSelectedParticipantChange,
}: DualMapViewProps) {
  const [mode, setMode] = useState<MapMode>(initialMode);
  const [activeView, setActiveView] = useState<'outdoor' | 'indoor'>('outdoor');
  // Use prop if provided, otherwise manage internally
  const [selectedParticipantInternal, setSelectedParticipantInternal] = useState<Participant | null>(null);
  const selectedParticipant = selectedParticipantProp !== undefined ? selectedParticipantProp : selectedParticipantInternal;
  const setSelectedParticipant = onSelectedParticipantChange || setSelectedParticipantInternal;
  const [selectedWaypoint, setSelectedWaypoint] = useState<Waypoint | null>(null);

  // Get route state from store
  const { activeRoute, clearRoute } = useRoomStore();

  // Auto-detect indoor/outdoor based on location
  useEffect(() => {
    if (mode !== 'auto' || !currentLocation) return;

    const isIndoor = isInC3NavArea(currentLocation.latitude, currentLocation.longitude);
    setActiveView(isIndoor ? 'indoor' : 'outdoor');
  }, [mode, currentLocation]);

  // Manual toggle
  const toggleView = useCallback(() => {
    setMode('outdoor'); // Switch to manual mode
    setActiveView((prev) => (prev === 'outdoor' ? 'indoor' : 'outdoor'));
  }, []);

  // Force outdoor
  const goOutdoor = useCallback(() => {
    setMode('outdoor');
    setActiveView('outdoor');
  }, []);

  // Force indoor
  const goIndoor = useCallback(() => {
    setMode('indoor');
    setActiveView('indoor');
  }, []);

  // Handle participant click - show navigation panel
  const handleParticipantClick = useCallback((participant: Participant) => {
    setSelectedParticipant(participant);
    setSelectedWaypoint(null);
    onParticipantClick?.(participant);
  }, [onParticipantClick, setSelectedParticipant]);

  // Handle waypoint click - show navigation panel
  const handleWaypointClick = useCallback((waypoint: Waypoint) => {
    setSelectedWaypoint(waypoint);
    setSelectedParticipant(null);
    onWaypointClick?.(waypoint);
  }, [onWaypointClick, setSelectedParticipant]);

  // Close navigation panel
  const closeNavigationPanel = useCallback(() => {
    setSelectedParticipant(null);
    setSelectedWaypoint(null);
  }, [setSelectedParticipant]);

  return (
    <div className="relative w-full h-full">
      {/* Map view */}
      {activeView === 'outdoor' ? (
        <MapView
          participants={participants}
          waypoints={waypoints}
          currentUserId={currentUserId}
          onParticipantClick={handleParticipantClick}
          onWaypointClick={handleWaypointClick}
          zoomToLocation={zoomToLocation}
          routeSegments={activeRoute?.segments}
          routeLoading={activeRoute?.isLoading}
          routeError={activeRoute?.error}
          routeSummary={activeRoute?.summary}
          routeDistance={activeRoute?.totalDistance}
          routeTime={activeRoute?.estimatedTime}
          routeDestination={activeRoute?.to.name}
          onClearRoute={clearRoute}
        />
      ) : (
        <C3NavEmbed
          eventId={eventId}
          participants={participants}
          currentUserId={currentUserId}
          onToggleOutdoor={goOutdoor}
        />
      )}

      {/* Navigation panel for selected participant/waypoint */}
      {(selectedParticipant || selectedWaypoint) && (
        <NavigationPanel
          selectedParticipant={selectedParticipant}
          selectedWaypoint={selectedWaypoint}
          currentLocation={currentLocation}
          allParticipants={participants}
          waypoints={waypoints}
          currentUserId={currentUserId}
          onClose={closeNavigationPanel}
        />
      )}

      {/* Location sharing button - floating inside map at bottom right for mobile visibility */}
      {onToggleSharing && (
        <button
          onClick={onToggleSharing}
          className={`absolute bottom-20 right-4 z-30 flex items-center gap-2 px-4 py-3 rounded-full shadow-lg transition-all ${
            isSharing
              ? 'bg-rmaps-primary text-white'
              : 'bg-white text-gray-800 hover:bg-gray-100'
          }`}
          title={isSharing ? 'Stop sharing location' : 'Share my location'}
        >
          <svg
            className="w-5 h-5"
            fill={isSharing ? 'currentColor' : 'none'}
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
            />
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
            />
          </svg>
          <span className="text-sm font-medium hidden sm:inline">
            {isSharing ? 'Sharing' : 'Share Location'}
          </span>
        </button>
      )}


      {/* Venue proximity indicator */}
      {currentLocation && isInC3NavArea(currentLocation.latitude, currentLocation.longitude) && activeView === 'outdoor' && (
        <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-rmaps-secondary/90 text-white text-sm px-3 py-1.5 rounded-full z-30">
          <span>You&apos;re at the venue!</span>
        </div>
      )}
    </div>
  );
}
