'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';

export interface FreelancerProfile {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  profileImage: string;
  rating: number;
  reviewCount: number;
  profileCompletion: number;
  bio?: string;
  hourlyRate?: number;
  availability?: string;
  skills?: string[];
  phone?: string;
  country?: string;
  city?: string;
  zipCode?: string;
}

export interface UseFreelancerProfileReturn {
  profile: FreelancerProfile | null;
  isLoading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export function useFreelancerProfile(): UseFreelancerProfileReturn {
  const { data: session, status } = useSession();
  const [profile, setProfile] = useState<FreelancerProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchProfile = async () => {
    if (status !== 'authenticated' || !session?.user?.email) {
      setIsLoading(false);
      return;
    }

    try {
      setError(null);
      const response = await fetch('/api/freelancer/profile', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch profile');
      }

      const data = await response.json();
      if (data.success) {
        setProfile(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch profile');
      }
    } catch (err: any) {
      console.error('Error fetching profile:', err);
      setError(err.message || 'Failed to load profile');
      // Set fallback profile data
      setProfile({
        id: session.user.email,
        firstName: session.user.name?.split(' ')[0] || 'Freelancer',
        lastName: session.user.name?.split(' ').slice(1).join(' ') || '',
        email: session.user.email,
        profileImage: session.user.image || '/assets/image/profile03.png',
        rating: 4.5,
        reviewCount: 0,
        profileCompletion: 50,
      });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchProfile();
  }, [status, session?.user?.email]);

  return {
    profile,
    isLoading,
    error,
    refetch: fetchProfile,
  };
}