import React, { useMemo, useState } from 'react';
import useRoleDetection from '@/hooks/useRoleDetection';
import { useFounders } from '@/hooks/useFounders';
import { useAuth } from '@/context/AuthContext';
import RoleDirectoryList from '@/components/directory/RoleDirectoryList';
import { useConnections } from '@/hooks/useConnections';
import { toast } from 'sonner';

const Founders = () => {
  const { user } = useAuth();
  const { founders, isLoading, error } = useFounders();
  const { sendConnectionRequest, loading: connectionLoading } = useConnections();
  const { isContributor, isInvestor } = useRoleDetection();
  const [pendingConnections, setPendingConnections] = useState<string[]>([]);

  // Define who this user can connect to as per their role
  function canConnect(rowRoleArr: string[]): boolean {
    if (!user) return false;
    
    // Don't allow connecting to yourself
    if (rowRoleArr.includes('self')) return false;
    
    if (isContributor) return rowRoleArr.includes("founder") || rowRoleArr.includes("entrepreneur");
    if (isInvestor) return rowRoleArr.includes("founder") || rowRoleArr.includes("entrepreneur");
    return false; // Founders don't connect with other founders
  }

  const handleConnect = async (targetId: string) => {
    if (!targetId || !user) {
      toast.error('You must be logged in to send connection requests');
      return;
    }
    
    // Don't allow connecting to yourself
    if (targetId === user.id) {
      toast.error('You cannot connect with yourself');
      return;
    }

    try {
      // Track pending connection to prevent multiple clicks
      setPendingConnections(prev => [...prev, targetId]);
      
      await sendConnectionRequest(targetId);
      
      // No need to remove from pending if successful as the UI will update
      // to show it's connected after a refresh
    } catch (error) {
      console.error('Connection request failed:', error);
      toast.error('Failed to send connection request. Please try again.');
    } finally {
      // Remove from pending status
      setPendingConnections(prev => prev.filter(id => id !== targetId));
    }
  };

  // Map founders to generic directory structure using useMemo for optimization
  const directoryUsers = useMemo(() => founders.map((f) => ({
    id: f.id,
    full_name: f.full_name,
    avatar_url: f.avatar_url,
    bio: f.bio,
    roleLabels: f.id === user?.id ? ['self'] : ["founder"], // Mark own profile as 'self'
    onConnect: (targetId: string) => handleConnect(targetId),
    canConnect: user && f.id !== user.id && canConnect(f.id === user?.id ? ['self'] : ["founder"]),
    isPendingConnection: pendingConnections.includes(f.id),
  })), [founders, user, isContributor, isInvestor, pendingConnections]);

  return (
    <div className="min-h-screen flex flex-col">
      <main className="flex-grow container mx-auto px-4 py-8 mt-16">
        <h1 className="text-3xl font-bold mb-8">Founders</h1>
        <RoleDirectoryList
          users={directoryUsers}
          currentUserId={user?.id || ""}
          roleLabel="Founders"
          isLoading={isLoading}
          error={error?.message}
          isConnecting={connectionLoading}
        />
      </main>
    </div>
  );
};

export default Founders;
move the connect button from founder as it's our own with twhich we have logged in as a founder role