import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Button, Typography, message } from 'antd';
import { UserAddOutlined, CloseOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useSocialStore } from '@/stores/social.store';
import UserAvatar from './UserAvatar';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface Suggestion {
  userId: string;
  name: string | null;
  email: string;
  role: string;
  reason: string;
  score: number;
}

interface FriendSuggestionsProps {
  limit?: number;
}

export default function FriendSuggestions({ limit = 5 }: FriendSuggestionsProps) {
  const navigate = useNavigate();
  const { sendFriendRequest } = useSocialStore();
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  useEffect(() => {
    loadSuggestions();
  }, []);

  const loadSuggestions = async () => {
    try {
      const { data } = await api.get('/social/suggestions', { params: { limit } });
      setSuggestions(data.suggestions);
    } catch {} finally {
      setLoading(false);
    }
  };

  const handleAdd = async (userId: string) => {
    setActionLoading(userId);
    try {
      await sendFriendRequest(userId);
      message.success('Friend request sent');
      setSuggestions((prev) => prev.filter((s) => s.userId !== userId));
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to send request'));
    } finally {
      setActionLoading(null);
    }
  };

  const handleDismiss = async (userId: string) => {
    try {
      await api.post(`/social/suggestions/${userId}/dismiss`);
      setSuggestions((prev) => prev.filter((s) => s.userId !== userId));
    } catch {}
  };

  if (loading || suggestions.length === 0) return null;

  return (
    <Card size="small" title="People you may know" style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', overflowX: 'auto', gap: 10, padding: '4px 0' }}>
        {suggestions.map((s) => (
          <div
            key={s.userId}
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              minWidth: 110,
              maxWidth: 110,
              textAlign: 'center',
              position: 'relative',
            }}
          >
            <Button
              type="text"
              size="small"
              icon={<CloseOutlined />}
              style={{ position: 'absolute', top: -6, right: -6, fontSize: 10, opacity: 0.5 }}
              onClick={() => handleDismiss(s.userId)}
            />
            <div
              style={{ cursor: 'pointer' }}
              onClick={() => navigate(`/volunteer/profile/${s.userId}`)}
            >
              <UserAvatar userId={s.userId} name={s.name} email={s.email} size={44} />
            </div>
            <Typography.Text
              ellipsis
              style={{ fontSize: 12, fontWeight: 500, marginTop: 4, maxWidth: 100 }}
            >
              {s.name || s.email}
            </Typography.Text>
            <Typography.Text type="secondary" style={{ fontSize: 10, lineHeight: '14px' }}>
              {s.reason}
            </Typography.Text>
            <Button
              type="primary"
              size="small"
              icon={<UserAddOutlined />}
              loading={actionLoading === s.userId}
              onClick={() => handleAdd(s.userId)}
              style={{ marginTop: 4, fontSize: 11 }}
            >
              Add
            </Button>
          </div>
        ))}
      </div>
    </Card>
  );
}
