'use client';

import React, { useState, useCallback, useMemo } from 'react';
import type { Participant } from '@/types';

interface ParticipantListProps {
  participants: Participant[];
  currentUserId?: string;
  roomSlug: string;
  syncUrl?: string;
  onClose: () => void;
  onNavigateTo: (participant: Participant) => void;
  onSetMeetingPoint?: () => void;
  onImportPlaces?: () => void;
}

export default function ParticipantList({
  participants,
  currentUserId,
  roomSlug,
  syncUrl,
  onClose,
  onNavigateTo,
  onSetMeetingPoint,
  onImportPlaces,
}: ParticipantListProps) {
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [pingingUser, setPingingUser] = useState<string | null>(null);
  const [refreshMessage, setRefreshMessage] = useState<string | null>(null);

  // Ping all users in the room
  const handlePingAll = useCallback(async () => {
    if (!syncUrl || isRefreshing) return;

    setIsRefreshing(true);
    setRefreshMessage(null);

    try {
      const httpUrl = syncUrl.replace('wss://', 'https://').replace('ws://', 'http://');
      const response = await fetch(`${httpUrl}/push/request-location`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ roomSlug }),
      });

      const data = await response.json();
      if (data.success) {
        const total = data.total || (data.websocket || 0) + (data.push || 0);
        if (total > 0) {
          setRefreshMessage(`Pinged ${total} friend${total > 1 ? 's' : ''}`);
        } else {
          setRefreshMessage('No friends to ping');
        }
      }
    } catch (error) {
      console.error('Failed to ping all:', error);
      setRefreshMessage('Failed to ping');
    } finally {
      setIsRefreshing(false);
      setTimeout(() => setRefreshMessage(null), 3000);
    }
  }, [syncUrl, roomSlug, isRefreshing]);

  // Ping a single user
  const handlePingUser = useCallback(async (participantId: string, participantName: string) => {
    if (!syncUrl || pingingUser) return;

    setPingingUser(participantId);
    setRefreshMessage(null);

    try {
      const httpUrl = syncUrl.replace('wss://', 'https://').replace('ws://', 'http://');
      const response = await fetch(`${httpUrl}/push/request-location`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ roomSlug, participantId }),
      });

      const data = await response.json();
      if (data.success) {
        setRefreshMessage(`Pinged ${participantName}`);
      } else {
        setRefreshMessage(`Couldn't reach ${participantName}`);
      }
    } catch (error) {
      console.error('Failed to ping user:', error);
      setRefreshMessage('Failed to ping');
    } finally {
      setPingingUser(null);
      setTimeout(() => setRefreshMessage(null), 3000);
    }
  }, [syncUrl, roomSlug, pingingUser]);
  const formatDistance = (participant: Participant, current: Participant | undefined) => {
    if (!participant.location || !current?.location) return null;

    // Haversine distance calculation
    const R = 6371e3; // Earth radius in meters
    const lat1 = (current.location.latitude * Math.PI) / 180;
    const lat2 = (participant.location.latitude * Math.PI) / 180;
    const deltaLat =
      ((participant.location.latitude - current.location.latitude) * Math.PI) / 180;
    const deltaLng =
      ((participant.location.longitude - current.location.longitude) * Math.PI) / 180;

    const a =
      Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
      Math.cos(lat1) *
        Math.cos(lat2) *
        Math.sin(deltaLng / 2) *
        Math.sin(deltaLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c;

    if (distance < 50) return 'nearby';
    if (distance < 1000) return `${Math.round(distance)}m`;
    return `${(distance / 1000).toFixed(1)}km`;
  };

  // Deduplicate participants by name, keeping the most recently seen one
  const deduplicatedParticipants = useMemo(() => {
    const byName = new Map<string, typeof participants[0]>();
    for (const p of participants) {
      const existing = byName.get(p.name);
      if (!existing || p.lastSeen > existing.lastSeen) {
        byName.set(p.name, p);
      }
    }
    return Array.from(byName.values());
  }, [participants]);

  const currentParticipant = deduplicatedParticipants.find((p) => p.name === currentUserId);

  return (
    <div className="room-panel h-full md:h-auto md:max-h-[calc(100vh-4rem)] rounded-t-2xl md:rounded-2xl md:m-4 overflow-hidden flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-white/10">
        <h2 className="font-semibold">Friends ({deduplicatedParticipants.length})</h2>
        <div className="flex items-center gap-2">
          {/* Ping all friends button */}
          {syncUrl && (
            <button
              onClick={handlePingAll}
              disabled={isRefreshing}
              className="p-1.5 rounded hover:bg-white/10 transition-colors disabled:opacity-50"
              title="Ping all friends for location updates"
            >
              <svg
                className={`w-5 h-5 ${isRefreshing ? 'animate-pulse' : ''}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                {/* Bell with broadcast brackets */}
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
                />
                {/* Left bracket */}
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M2 8c0-1 .5-2 1.5-3M2 16c0 1 .5 2 1.5 3"
                />
                {/* Right bracket */}
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M22 8c0-1-.5-2-1.5-3M22 16c0 1-.5 2-1.5 3"
                />
              </svg>
            </button>
          )}
          <button
            onClick={onClose}
            className="p-1 rounded hover:bg-white/10 transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
      </div>

      {/* Refresh status message */}
      {refreshMessage && (
        <div className="px-4 py-2 bg-rmaps-primary/20 text-rmaps-primary text-sm text-center">
          {refreshMessage}
        </div>
      )}

      {/* Participant list */}
      <div className="flex-1 overflow-y-auto p-2">
        {deduplicatedParticipants.length === 0 ? (
          <div className="text-center text-white/40 py-8">
            No one else is here yet
          </div>
        ) : (
          <div className="space-y-1">
            {deduplicatedParticipants.map((participant) => {
              const isMe = participant.name === currentUserId;
              const distance = !isMe
                ? formatDistance(participant, currentParticipant)
                : null;

              return (
                <div
                  key={participant.id}
                  className="participant-item cursor-pointer"
                  onClick={() => !isMe && onNavigateTo(participant)}
                >
                  {/* Avatar */}
                  <div
                    className="w-10 h-10 rounded-full flex items-center justify-center text-xl"
                    style={{ backgroundColor: participant.color }}
                  >
                    {participant.emoji}
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-medium truncate">
                        {participant.name}
                        {isMe && (
                          <span className="text-white/40 text-sm ml-1">(you)</span>
                        )}
                      </span>
                      <div className={`status-dot ${participant.status}`} />
                    </div>
                    {participant.location && (
                      <div className="text-xs text-white/40">
                        {distance ? `${distance} away` : 'Location shared'}
                      </div>
                    )}
                    {participant.status === 'ghost' && (
                      <div className="text-xs text-white/40">Location hidden</div>
                    )}
                  </div>

                  {/* Action buttons */}
                  {!isMe && (
                    <div className="flex items-center gap-1">
                      {/* Ping single user button */}
                      {syncUrl && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handlePingUser(participant.id, participant.name);
                          }}
                          disabled={pingingUser === participant.id}
                          className="p-2 rounded-lg bg-white/10 hover:bg-white/20 transition-colors disabled:opacity-50"
                          title={`Ping ${participant.name}`}
                        >
                          <svg
                            className={`w-4 h-4 ${pingingUser === participant.id ? 'animate-pulse' : ''}`}
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
                            />
                          </svg>
                        </button>
                      )}
                      {/* Navigate button */}
                      {participant.location && (
                        <button
                          className="p-2 rounded-lg bg-white/10 hover:bg-white/20 transition-colors"
                          title="Navigate to"
                        >
                          <svg
                            className="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7"
                            />
                          </svg>
                        </button>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer actions */}
      <div className="p-4 border-t border-white/10 space-y-2">
        <button
          className="btn-secondary w-full text-sm"
          onClick={onSetMeetingPoint}
        >
          Set Meeting Point
        </button>
        <button
          className="btn-ghost w-full text-sm flex items-center justify-center gap-2"
          onClick={onImportPlaces}
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
            />
          </svg>
          Import Places
        </button>
      </div>
    </div>
  );
}
