import useSWR from 'swr';
import { useState, useCallback, useEffect } from 'react';
import { fileManagerApi } from '@/shared/api/file-manager';
import { getUserByEmail } from '@/shared/api/user';

export function useDocuments(viewType: 'PERSONAL' | 'SHARED' | 'SHARED_WITH_ME') {
  const [user, setUser] = useState<any>(null);

  
  const fetcher = async () => {
    if (!user) throw new Error('User not loaded');
    switch (viewType) {
      case 'PERSONAL':
        return fileManagerApi.getPersonalDocuments();
      case 'SHARED_WITH_ME':
        return fileManagerApi.getSharedWithMeDocuments();
      case 'SHARED': {
        const agencyId = localStorage.getItem('selectedAgency');
        if (!agencyId) throw new Error('No agencyId found');
        return fileManagerApi.getSharedDocuments(Number(agencyId));
      }
      default:
        throw new Error('Unknown view type');
    }
  };

  useEffect(() => {
    const loadUser = async () => {
      try {
        const email = localStorage.getItem('email');
        if (!email) throw new Error('No email found in localStorage');
        const userData = await getUserByEmail(email);
        setUser(userData);
      } catch (error) {
        console.error('Error fetching user:', error);
      }
    };
 
    loadUser(); 
  }, []); 

  const { data: documents, error, isLoading, mutate } = useSWR(
    user ? ['documents', viewType] : null, 
    fetcher
  );
  const toggleFavorite = useCallback(
    async (uniqueId: string, isFavorited: boolean): Promise<boolean> => {
      try {
        if (isFavorited) {
          await fileManagerApi.unmarkAsFavorite(uniqueId);
        } else {
          await fileManagerApi.markAsFavorite(uniqueId);
        }
        mutate(
          (currentData: any[]) =>
            currentData?.map((doc) =>
              doc.uniqueId === uniqueId ? { ...doc, isFavorited: !isFavorited } : doc
            ),
          false 
        );

        return true;
      } catch (error) {
        console.error('Error toggling favorite:', error);
        return false;
      }
    },
    [mutate]
  );
  const refetch = useCallback(() => {
    mutate();
  }, [mutate]);

  return {
    documents,
    loading: isLoading,
    error,
    refetch,
    toggleFavorite,
    notFound: !documents || documents.length === 0,
  };
}
