import { useEffect, useState } from "react";
import { DirectoryRepository } from "../repositories/DirectoryRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager";

export const useDirectory = (isActive,prefernceContacts) => {
  const [contacts, setContacts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetch = async (activeParam = isActive) => {
    setLoading(true);
    try {
      const response = await DirectoryRepository.GetContacts(activeParam,prefernceContacts);
      setContacts(response.data);
      cacheData("contacts", { data: response.data, isActive: activeParam });
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const cachedContacts = getCachedData("contacts");
    if (!cachedContacts?.data || cachedContacts.isActive !== isActive || prefernceContacts) {
      fetch(isActive,prefernceContacts);
    } else {
      setContacts(cachedContacts.data);
    }
  }, [isActive,prefernceContacts]);

  return {
    contacts,
    loading,
    error,
    refetch: fetch,
  };
};

export const useBuckets = () => {
  const [buckets, setBuckets] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const fetchBuckets = async () => {
    setLoading(true);
    try {
      const resp = await DirectoryRepository.GetBucktes();
      setBuckets(resp.data);
      cacheData("buckets", resp.data);
      setLoading(false);
    } catch (error) {
      const msg =
        error?.response?.data?.message ||
        error?.message ||
        "Something went wrong";
      setError( msg );
      setLoading(false);
    }
  };

  useEffect(() => {
    const cacheBuckets = getCachedData("buckets");
    if (!cacheBuckets) {
      fetchBuckets();
    } else {
      setBuckets(cacheBuckets);
    }
  }, []);

  return { buckets, loading, error, refetch: fetchBuckets };
};

export const useContactProfile = (id) => {
  const [contactProfile, setContactProfile] = useState(null);
  const [loading, setLoading] = useState(false);
  const [Error, setError] = useState("");

  const fetchContactProfile = async () => {

      setLoading(true);
      try {
        const resp = await DirectoryRepository.GetContactProfile(id);
        setContactProfile(resp.data);
        cacheData("Contact Profile", { data: resp.data, contactId: id });
      } catch (err) {
        const msg =
          err?.response?.data?.message ||
          err?.message ||
          "Something went wrong";
        setError(msg);
      } finally {
        setLoading(false);
      }
    
  };

  useEffect( () =>
  {
    const cached = getCachedData("Contact Profile");
       if (!cached || cached.contactId !== id) {
      fetchContactProfile(id);
    } else {
      setContactProfile(cached.data);
    }
  }, [id]);

  return { contactProfile, loading, Error ,refetch:fetchContactProfile};
};

export const useContactNotes = (id, IsActive) => {
  const [contactNotes, setContactNotes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [Error, setError] = useState("");

  const fetchContactNotes = async (id,IsActive) => {
   

      setLoading(true);
      try {
        const resp = await DirectoryRepository.GetNote(id, IsActive);
        setContactNotes(resp.data);
        cacheData("Contact Notes", { data: resp.data, contactId: id });
      } catch (err) {
        const msg =
          err?.response?.data?.message ||
          err?.message ||
          "Something went wrong";
        setError(msg);
      } finally {
        setLoading(false);
      }
   
  };

  useEffect(() => {
    const cached = getCachedData("Contact Notes");
    if (!cached || cached.contactId !== id) {
      id && fetchContactNotes(id,IsActive);
     } else {
      setContactNotes(cached.data);
    }
  }, [id,IsActive]);

  return { contactNotes, loading, Error,refetch:fetchContactNotes };
};

export const useOrganization = () => {
  const [organizationList, setOrganizationList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const fetchOrg = async () => {
    const cacheOrg = getCachedData("organizations");
    if (cacheOrg?.length != 0) {
      setLoading(true);
      try {
        const resp = await DirectoryRepository.GetOrganizations();
        cacheData("organizations", resp.data);
        setOrganizationList(resp.data);
        setLoading(false);
      } catch (error) {
        const msg =
          error?.response?.data?.message ||
          error?.message ||
          "Something went wrong";
        setError(msg);
      }
    } else {
      setOrganizationList(cacheOrg);
    }
  };

  useEffect(() => {
    fetchOrg();
  }, []);

  return { organizationList, loading, error };
};
