'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { ProfileTemplate } from '@/templates/ProfileTemplate';
import { type ProfileTab } from '@/components/profile/ProfileNavTabs';
import type { ProfileViewData } from '@/lib/view-data/ProfileViewData';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';

interface ProfilePageClientProps extends ClientWrapperProps<ProfileViewData> {
  mode: 'profile-exists' | 'needs-profile';
}

export function ProfilePageClient({ viewData, mode }: ProfilePageClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const tabParam = searchParams.get('tab') as ProfileTab | null;

  const [activeTab, setActiveTab] = useState<ProfileTab>(tabParam || 'overview');
  const [friendRequestSent, setFriendRequestSent] = useState(false);

  useEffect(() => {
    const params = new URLSearchParams(searchParams.toString());
    if (activeTab === 'overview') {
      params.delete('tab');
    } else {
      params.set('tab', activeTab);
    }
    const query = params.toString();
    const currentQuery = searchParams.toString();
    
    if (query !== currentQuery) {
      router.replace(`/profile${query ? `?${query}` : ''}`, { scroll: false });
    }
  }, [activeTab, searchParams, router]);

  useEffect(() => {
    const tab = searchParams.get('tab') as ProfileTab | null;
    if (tab && tab !== activeTab) {
      setActiveTab(tab);
    }
  }, [searchParams, activeTab]);

  return (
    <ProfileTemplate
      viewData={viewData}
      mode={mode}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      friendRequestSent={friendRequestSent}
      onFriendRequestSend={() => setFriendRequestSent(true)}
    />
  );
}
