// src/contexts/ProfileContext.tsx
import { createContext, useContext, useState } from 'react';

interface ProfileData {
  name: string;
  email: string;
  profileImage: string;
  company_id: string;
  plan_id: string;
  start_date: string;
  end_date: string;
  address: string;
  country: string;
  state: string;
  city: string;
  zip: string;
}

interface ProfileContextType {
  profile: ProfileData;
  setProfile: React.Dispatch<React.SetStateAction<ProfileData>>;
  fetchProfileData: () => Promise<void>;
}

const ProfileContext = createContext<ProfileContextType>({
  profile: {
    name: '',
    email: '',
    profileImage: '/assets/images/profile.png',
    company_id: '',
    plan_id: '',
    start_date: '',
    end_date: '',
    address: '',
    country: '',
    state: '',
    city: '',
    zip: ''
  },
  setProfile: () => {},
  fetchProfileData: async () => {}
});

export const useProfile = () => useContext(ProfileContext);

export const ProfileProvider = ({ children }: { children: React.ReactNode }) => {
  const [profile, setProfile] = useState<ProfileData>({
    name: '',
    email: '',
    profileImage: '/assets/images/profile.png',
    company_id: '',
    plan_id: '',
    start_date: '',
    end_date: '',
    address: '',
    country: '',
    state: '',
    city: '',
    zip: ''
  });

  const fetchProfileData = async () => {
    try {
      const response = await fetch('/api/get_profiledata_company_admin', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ user_id: localStorage.getItem('userId') }),
      });

      const data = await response.json();

      if (data.status === 'success') {
        setProfile({
          name: data.data.name || '',
          email: data.data.email || '',
          profileImage: data.data.profile_image || '/assets/images/profile.png',
          company_id: data.data.company_id || '',
          plan_id: data.data.plan_id || '',
          start_date: data.data.start_date || '',
          end_date: data.data.end_date || '',
          address: data.data.address || '',
          country: data.data.country || '',
          state: data.data.state || '',
          city: data.data.city || '',
          zip: data.data.zip || ''
        });
      }
    } catch (error) {
      console.error('Error fetching profile data:', error);
    }
  };

  return (
    <ProfileContext.Provider value={{ profile, setProfile, fetchProfileData }}>
      {children}
    </ProfileContext.Provider>
  );
};