import { useState, useEffect } from 'react';
import { Badge, Tooltip, List, Typography } from 'antd';
import { TeamOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const { Text } = Typography;

interface MapFriend {
  id: string;
  name: string | null;
  email: string;
  cutName: string;
  cutId: number;
  startedAt: string;
}

interface Props {
  /** Callback when user clicks a friend (e.g. to pan to their area) */
  onFriendClick?: (friend: MapFriend) => void;
}

/**
 * Floating panel showing friends currently canvassing.
 * Designed to overlay on the volunteer map.
 */
export default function FriendsOnMap({ onFriendClick }: Props) {
  const { isAuthenticated } = useAuthStore();
  const { settings } = useSettingsStore();
  const [friends, setFriends] = useState<MapFriend[]>([]);
  const [collapsed, setCollapsed] = useState(false);

  useEffect(() => {
    if (!isAuthenticated || !settings?.enableSocial) return;

    const fetch = () => {
      api.get('/social/integration/map/friends')
        .then(({ data }) => setFriends(data.friends || []))
        .catch(() => {});
    };

    fetch();
    // Refresh every 60 seconds
    const interval = setInterval(fetch, 60_000);
    return () => clearInterval(interval);
  }, [isAuthenticated, settings?.enableSocial]);

  if (!isAuthenticated || !settings?.enableSocial || friends.length === 0) return null;

  return (
    <div
      style={{
        position: 'absolute',
        top: 10,
        right: 10,
        zIndex: 1000,
        background: 'rgba(13, 27, 42, 0.92)',
        borderRadius: 8,
        border: '1px solid rgba(255,255,255,0.12)',
        minWidth: collapsed ? 'auto' : 220,
        maxWidth: 280,
        backdropFilter: 'blur(8px)',
        overflow: 'hidden',
      }}
    >
      <div
        onClick={() => setCollapsed((c) => !c)}
        style={{
          padding: '8px 12px',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          borderBottom: collapsed ? 'none' : '1px solid rgba(255,255,255,0.08)',
        }}
      >
        <Badge count={friends.length} size="small" color="#52c41a">
          <TeamOutlined style={{ color: '#52c41a', fontSize: 16 }} />
        </Badge>
        <Text style={{ color: '#fff', fontSize: 13, fontWeight: 500 }}>
          Friends Canvassing
        </Text>
      </div>

      {!collapsed && (
        <List
          size="small"
          dataSource={friends}
          style={{ maxHeight: 200, overflow: 'auto' }}
          renderItem={(friend) => (
            <List.Item
              style={{
                padding: '6px 12px',
                cursor: onFriendClick ? 'pointer' : 'default',
                borderBottom: '1px solid rgba(255,255,255,0.04)',
              }}
              onClick={() => onFriendClick?.(friend)}
            >
              <div>
                <Tooltip title={friend.email}>
                  <Text style={{ color: '#fff', fontSize: 12, fontWeight: 500 }}>
                    {friend.name || friend.email}
                  </Text>
                </Tooltip>
                <br />
                <Text style={{ color: 'rgba(255,255,255,0.45)', fontSize: 11 }}>
                  {friend.cutName} · started {dayjs(friend.startedAt).fromNow()}
                </Text>
              </div>
            </List.Item>
          )}
        />
      )}
    </div>
  );
}
