import { useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Typography, Input, List, Empty, Skeleton, Card } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import UserAvatar from '@/components/social/UserAvatar';
import FriendSuggestions from '@/components/social/FriendSuggestions';
import FriendButton from '@/components/social/FriendButton';
import type { FriendshipStatusResponse } from '@/types/social';

interface SearchResult {
  id: string;
  name: string | null;
  email: string;
  role: string;
  createdAt: string;
}

interface SearchResultWithStatus extends SearchResult {
  friendshipStatus?: FriendshipStatusResponse;
}

export default function DiscoverPage() {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState<SearchResultWithStatus[]>([]);
  const [searching, setSearching] = useState(false);
  const [searched, setSearched] = useState(false);

  const handleSearch = useCallback(async (term: string) => {
    if (term.trim().length < 2) {
      setResults([]);
      setSearched(false);
      return;
    }

    setSearching(true);
    setSearched(true);
    try {
      // Search users by name/email
      const { data } = await api.get('/users', { params: { search: term, limit: 20, page: 1 } });
      const users: SearchResult[] = data.users || [];

      // Fetch friendship status for each result in parallel
      const withStatus = await Promise.all(
        users.map(async (u) => {
          try {
            const { data: status } = await api.get(`/social/friends/status/${u.id}`);
            return { ...u, friendshipStatus: status as FriendshipStatusResponse };
          } catch {
            return { ...u, friendshipStatus: { status: 'none' } as FriendshipStatusResponse };
          }
        }),
      );

      setResults(withStatus);
    } catch {
      setResults([]);
    } finally {
      setSearching(false);
    }
  }, []);

  // Debounced search on input change
  const [debounceTimer, setDebounceTimer] = useState<ReturnType<typeof setTimeout> | null>(null);
  const onSearchChange = (value: string) => {
    setSearchTerm(value);
    if (debounceTimer) clearTimeout(debounceTimer);
    setDebounceTimer(setTimeout(() => handleSearch(value), 400));
  };

  const refreshResult = async (userId: string) => {
    try {
      const { data: status } = await api.get(`/social/friends/status/${userId}`);
      setResults((prev) =>
        prev.map((r) => (r.id === userId ? { ...r, friendshipStatus: status } : r)),
      );
    } catch {}
  };

  return (
    <div style={{ padding: '12px 0' }}>
      <Typography.Title level={4} style={{ margin: '0 0 12px 0' }}>Discover People</Typography.Title>

      <Input
        prefix={<SearchOutlined />}
        placeholder="Search by name or email..."
        value={searchTerm}
        onChange={(e) => onSearchChange(e.target.value)}
        size="large"
        allowClear
        style={{ marginBottom: 16 }}
      />

      {!searched && (
        <>
          <FriendSuggestions limit={10} />
          <Card size="small" style={{ textAlign: 'center' }}>
            <Typography.Text type="secondary">
              Search for volunteers by name or email to connect with them
            </Typography.Text>
          </Card>
        </>
      )}

      {searched && (
        <>
          {searching ? (
            <Skeleton active paragraph={{ rows: 4 }} />
          ) : results.length === 0 ? (
            <Empty description={`No users found for "${searchTerm}"`} />
          ) : (
            <List
              dataSource={results}
              renderItem={(r) => (
                <List.Item
                  actions={[
                    r.friendshipStatus && r.friendshipStatus.status !== 'self' && (
                      <FriendButton
                        key="action"
                        userId={r.id}
                        status={r.friendshipStatus}
                        onStatusChange={() => refreshResult(r.id)}
                        size="small"
                      />
                    ),
                  ].filter(Boolean)}
                >
                  <List.Item.Meta
                    avatar={
                      <div style={{ cursor: 'pointer' }} onClick={() => navigate(`/volunteer/profile/${r.id}`)}>
                        <UserAvatar userId={r.id} name={r.name} email={r.email} size={40} />
                      </div>
                    }
                    title={
                      <span style={{ cursor: 'pointer' }} onClick={() => navigate(`/volunteer/profile/${r.id}`)}>
                        {r.name || r.email}
                      </span>
                    }
                    description={r.name ? r.email : undefined}
                  />
                </List.Item>
              )}
            />
          )}
        </>
      )}
    </div>
  );
}
