'use client';

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

export interface ClientProfile {
  id: string;
  firstName: string | null;
  lastName: string | null;
  email: string;
  phone: string | null;
  country: string | null;
  city: string | null;
  profileImage: string;
  rating: number;
  reviewCount: number;
  profileCompletion: number;
  bio: string | null;
  createdAt: string;
  updatedAt: string;
}

interface UseClientProfileReturn {
  profile: ClientProfile | null;
  isLoading: boolean;
  error: string | null;
  refetch: () => void;
}

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

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

    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch('/api/client/profile');

      if (!response.ok) {
        if (response.status === 404) {
          setError('Profile not found');
          setProfile(null);
          return;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.success && data.data) {
        setProfile(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch profile');
      }
    } catch (err) {
      console.error('Error fetching client profile:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch profile');
      setProfile(null);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchProfile();
  }, [status, session]);

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