'use client';

import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { NetworkSidebar } from './component/NetworkSidebar';
import { InvitationCard } from './component/InvitationCard';
import { ConnectionCard } from './component/ConnectionCard';
import { connectionRequestsService, ConnectionRequest, ConnectionRequestCounts } from '@/services/connection-requests.service';
import { messagesService } from '@/services/messages.service';
import { uploadService } from '@/services/upload.service';

export default function NetworkPage() {
  const router = useRouter();
  const [pendingRequests, setPendingRequests] = useState<ConnectionRequest[]>([]);
  const [connections, setConnections] = useState<ConnectionRequest[]>([]);
  const [counts, setCounts] = useState<ConnectionRequestCounts>({ pending: 0, accepted: 0, rejected: 0, total: 0 });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [processingIds, setProcessingIds] = useState<Set<string>>(new Set());
  const [avatarUrls, setAvatarUrls] = useState<Record<string, string>>({});

  // Helper to check if a string is an S3 key (not a URL or local path)
  const isS3Key = (value: string | null | undefined): boolean => {
    if (!value) return false;
    return !value.startsWith('http') && !value.startsWith('/') && !value.startsWith('data:');
  };

  // Resolve S3 avatar keys to presigned URLs
  const resolveAvatars = useCallback(async (requests: ConnectionRequest[]) => {
    const newUrls: Record<string, string> = {};
    for (const req of requests) {
      const avatar = req.user?.userProfile?.avatar || req.user?.avatar;
      if (avatar && isS3Key(avatar) && !avatarUrls[req.id]) {
        try {
          newUrls[req.id] = await uploadService.getPresignedDownloadUrl(avatar);
        } catch {
          // Keep empty, will show placeholder
        }
      }
    }
    if (Object.keys(newUrls).length > 0) {
      setAvatarUrls(prev => ({ ...prev, ...newUrls }));
    }
  }, [avatarUrls]);

  // Fetch connection requests on mount
  useEffect(() => {
    fetchRequests();
  }, []);

  const fetchRequests = async () => {
    try {
      setLoading(true);
      setError(null);

      // Fetch pending requests, accepted connections, and counts in parallel
      const [pending, accepted, requestCounts] = await Promise.all([
        connectionRequestsService.getReceivedRequests('PENDING'),
        connectionRequestsService.getReceivedRequests('ACCEPTED'),
        connectionRequestsService.getRequestCounts(),
      ]);

      setPendingRequests(pending);
      setConnections(accepted);
      setCounts(requestCounts);

      // Resolve avatars for all requests
      resolveAvatars([...pending, ...accepted]);
    } catch (err) {
      console.error('Failed to fetch connection requests:', err);
      setError('Failed to load connection requests');
    } finally {
      setLoading(false);
    }
  };

  const handleAccept = async (id: string) => {
    if (processingIds.has(id)) return;

    try {
      setProcessingIds(prev => new Set([...prev, id]));
      const updatedRequest = await connectionRequestsService.respondToRequest(id, { status: 'ACCEPTED' });

      // Move from pending to connections
      const acceptedRequest = pendingRequests.find(r => r.id === id);
      if (acceptedRequest) {
        setPendingRequests(prev => prev.filter(r => r.id !== id));
        setConnections(prev => [{ ...acceptedRequest, ...updatedRequest }, ...prev]);
      }

      setCounts(prev => ({
        ...prev,
        pending: prev.pending - 1,
        accepted: prev.accepted + 1,
      }));
    } catch (err) {
      console.error('Failed to accept request:', err);
    } finally {
      setProcessingIds(prev => {
        const next = new Set(prev);
        next.delete(id);
        return next;
      });
    }
  };

  const handleIgnore = async (id: string) => {
    if (processingIds.has(id)) return;

    try {
      setProcessingIds(prev => new Set([...prev, id]));
      await connectionRequestsService.respondToRequest(id, { status: 'REJECTED' });

      // Remove from list and update counts
      setPendingRequests(prev => prev.filter(r => r.id !== id));
      setCounts(prev => ({
        ...prev,
        pending: prev.pending - 1,
        rejected: prev.rejected + 1,
      }));
    } catch (err) {
      console.error('Failed to reject request:', err);
    } finally {
      setProcessingIds(prev => {
        const next = new Set(prev);
        next.delete(id);
        return next;
      });
    }
  };

  const [messagingUserId, setMessagingUserId] = useState<string | null>(null);

  const handleMessage = async (userId: string) => {
    if (messagingUserId) return;
    setMessagingUserId(userId);
    try {
      const conversation = await messagesService.startConversation({ userId });
      router.push(`/agent/message?conversationId=${conversation.id}`);
    } catch (err) {
      console.error('Failed to start conversation:', err);
      router.push('/agent/message');
    } finally {
      setMessagingUserId(null);
    }
  };

  return (
    <div className="flex flex-col lg:flex-row gap-6">
      {/* Left Sidebar */}
      <NetworkSidebar counts={counts} />

      {/* Main Content */}
      <div className="flex-1 space-y-6">
        {/* Header Card */}
        <div className="border border-[#00293d]/10 rounded-[15px] px-6 py-4 bg-white">
          <h1 className="font-fractul font-bold text-[15px] leading-[18px] text-[#00293D]">
            Manage my network
          </h1>
        </div>

        {/* Loading State */}
        {loading && (
          <div className="border border-[#00293d]/10 rounded-[15px] bg-white">
            <div className="flex items-center justify-center py-12">
              <div className="flex flex-col items-center gap-4">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#E58625]"></div>
                <p className="text-[14px] font-serif text-[#00293D]/70">Loading network...</p>
              </div>
            </div>
          </div>
        )}

        {/* Error State */}
        {error && !loading && (
          <div className="border border-[#00293d]/10 rounded-[15px] bg-white">
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <p className="text-[14px] font-serif text-red-500 mb-2">{error}</p>
                <button
                  onClick={fetchRequests}
                  className="px-4 py-2 bg-[#E58625] rounded-full text-[14px] font-semibold text-white hover:bg-[#E58625]/90 transition-colors"
                >
                  Try Again
                </button>
              </div>
            </div>
          </div>
        )}

        {!loading && !error && (
          <>
            {/* Pending Connection Requests Card */}
            <div className="border border-[#00293d]/10 rounded-[15px] bg-white">
              {/* Requests Header */}
              <div className="flex items-center justify-between px-6 py-4 border-b border-[#00293d]/10">
                <h2 className="font-fractul font-bold text-[14px] leading-[17px] text-[#00293D]">
                  Pending Requests ({counts.pending})
                </h2>
              </div>

              {/* Empty State for Pending */}
              {pendingRequests.length === 0 && (
                <div className="flex items-center justify-center py-8">
                  <div className="text-center">
                    <div className="w-12 h-12 bg-[#00293D]/5 rounded-full flex items-center justify-center mx-auto mb-3">
                      <Image
                        src="/assets/icons/people-icon.svg"
                        alt="No requests"
                        width={24}
                        height={24}
                        className="opacity-30"
                      />
                    </div>
                    <h3 className="text-[14px] font-bold font-serif text-[#00293D] mb-1">No pending requests</h3>
                    <p className="text-[13px] font-serif text-[#00293D]/70">
                      New connection requests will appear here.
                    </p>
                  </div>
                </div>
              )}

              {/* Pending Requests List */}
              {pendingRequests.length > 0 && (
                <div className="px-6 divide-y divide-[#00293d]/10">
                  {pendingRequests.map((request) => {
                    const profile = request.user?.userProfile;
                    const userName = [profile?.firstName, profile?.lastName].filter(Boolean).join(' ') || request.user?.email || 'Unknown User';
                    const rawAvatar = profile?.avatar || request.user?.avatar;
                    const resolvedAvatar = avatarUrls[request.id] || (rawAvatar && !isS3Key(rawAvatar) ? rawAvatar : null);
                    return (
                    <InvitationCard
                      key={request.id}
                      id={request.id}
                      name={userName}
                      avatar={resolvedAvatar || '/assets/icons/user-placeholder-icon.svg'}
                      description={request.message || 'No message provided'}
                      createdAt={request.createdAt}
                      isProcessing={processingIds.has(request.id)}
                      onAccept={handleAccept}
                      onIgnore={handleIgnore}
                    />
                    );
                  })}
                </div>
              )}
            </div>

            {/* My Connections Card */}
            <div className="border border-[#00293d]/10 rounded-[15px] bg-white">
              {/* Connections Header */}
              <div className="flex items-center justify-between px-6 py-4 border-b border-[#00293d]/10">
                <h2 className="font-fractul font-bold text-[14px] leading-[17px] text-[#00293D]">
                  My Connections ({counts.accepted})
                </h2>
              </div>

              {/* Empty State for Connections */}
              {connections.length === 0 && (
                <div className="flex items-center justify-center py-8">
                  <div className="text-center">
                    <div className="w-12 h-12 bg-[#00293D]/5 rounded-full flex items-center justify-center mx-auto mb-3">
                      <Image
                        src="/assets/icons/people-icon.svg"
                        alt="No connections"
                        width={24}
                        height={24}
                        className="opacity-30"
                      />
                    </div>
                    <h3 className="text-[14px] font-bold font-serif text-[#00293D] mb-1">No connections yet</h3>
                    <p className="text-[13px] font-serif text-[#00293D]/70">
                      Accept connection requests to grow your network.
                    </p>
                  </div>
                </div>
              )}

              {/* Connections List */}
              {connections.length > 0 && (
                <div className="px-6 divide-y divide-[#00293d]/10">
                  {connections.map((connection) => {
                    const profile = connection.user?.userProfile;
                    const userName = [profile?.firstName, profile?.lastName].filter(Boolean).join(' ') || connection.user?.email || 'Unknown User';
                    const rawAvatar = profile?.avatar || connection.user?.avatar;
                    const resolvedAvatar = avatarUrls[connection.id] || (rawAvatar && !isS3Key(rawAvatar) ? rawAvatar : null);
                    return (
                    <ConnectionCard
                      key={connection.id}
                      id={connection.userId}
                      name={userName}
                      avatar={resolvedAvatar || '/assets/icons/user-placeholder-icon.svg'}
                      email={connection.user?.email || ''}
                      connectedAt={connection.respondedAt || connection.updatedAt}
                      onMessage={handleMessage}
                    />
                    );
                  })}
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
