import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { SearchInput } from '../../ui/input';
import { UserCard } from '../../user/UserCard';
import { User } from '../../../types';
import { useToast } from '../../../context/ToastContext';
import { Loader2 } from 'lucide-react';
import { searchService } from '../../../services/searchService';
import { logger } from '@/utils/logger';

interface ConnectionsViewProps {
  type: 'followers' | 'following';
  userId: string; // To fetch data
}

export const ConnectionsView: React.FC<ConnectionsViewProps> = ({
  type,
  userId,
}) => {
  const { addToast } = useToast();
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState<'all' | 'mutual' | 'recent'>('all');
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUsers = async () => {
      setLoading(true);
      try {
        // Simulating fetching followers/following via search service for now
        // In real app, call userService.getFollowers(userId)
        const res = await searchService.global('');
        setUsers(res.users);
      } catch (e) {
        logger.error('Error loading connections', {
          error: e instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined,
          type,
          userId,
        });
      } finally {
        setLoading(false);
      }
    };
    fetchUsers();
  }, [userId, type]);

  const filteredUsers = users.filter((u) =>
    u.username.toLowerCase().includes(search.toLowerCase()),
  );

  return (
    <div className="space-y-6 animate-fadeIn pb-20">
      <div className="flex flex-col md:flex-row justify-between items-end border-b border-kodo-steel/50 pb-6 gap-4">
        <div>
          <h2 className="text-3xl font-display font-bold text-white mb-2 capitalize">
            {type}
          </h2>
          <p className="text-gray-400 font-mono text-sm">
            Managing your network.
          </p>
        </div>
      </div>

      <div className="flex flex-col md:flex-row gap-4 items-center bg-kodo-ink/50 p-4 rounded-xl border border-kodo-steel/50">
        <div className="w-full md:w-96">
          <SearchInput
            placeholder={`Search ${type}...`}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        {type === 'followers' && (
          <div className="flex gap-2">
            <Button
              variant="ghost"
              size="sm"
              className={filter === 'all' ? 'text-white' : 'text-gray-500'}
              onClick={() => setFilter('all')}
            >
              All
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className={filter === 'mutual' ? 'text-white' : 'text-gray-500'}
              onClick={() => setFilter('mutual')}
            >
              Mutual
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className={filter === 'recent' ? 'text-white' : 'text-gray-500'}
              onClick={() => setFilter('recent')}
            >
              Recent
            </Button>
          </div>
        )}
      </div>

      {loading ? (
        <div className="flex justify-center py-20">
          <Loader2 className="w-10 h-10 text-kodo-cyan animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredUsers.map((user) => (
            <UserCard
              key={user.id}
              user={user}
              isFollowing={type === 'following'}
              onFollow={() =>
                addToast(type === 'following' ? 'Unfollowed' : 'Followed')
              }
              onView={() => addToast(`Viewing ${user.username}`)}
            />
          ))}
        </div>
      )}
    </div>
  );
};
