'use client';

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

interface ProfilePageClientProps {
  viewData: ProfileViewData;
  mode: 'profile-exists' | 'needs-profile';
  onSaveSettings: (updates: { bio?: string; country?: string }) => Promise<Result<void, string>>;
}

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

  const [activeTab, setActiveTab] = useState<ProfileTab>(tabParam || 'overview');
  const [editMode, setEditMode] = useState(false);
  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}
      editMode={editMode}
      onEditModeChange={setEditMode}
      friendRequestSent={friendRequestSent}
      onFriendRequestSend={() => setFriendRequestSent(true)}
      onSaveSettings={async (updates) => {
        const result = await onSaveSettings(updates);
        if (result.isErr()) {
          // In a real app, we'd show a toast or error message.
          // For now, we just throw to let the UI handle it if needed,
          // or we could add an error state to this client component.
          throw new Error(result.getError());
        }
      }}
    />
  );
}
