import { axiosInstance } from "@/utils/axios";
import { getUserByEmail } from "./user";

export enum AccessLevel {
    READ = 'READ',
    WRITE = 'WRITE',
}
interface UploadParams {
  file: File;
  section?: 'personal' | 'shared' | 'sharedWithMe';

}
interface CreateFolderParams {
  parentFolderId?: number | null;
  folderName: string;
  accessLevel?: AccessLevel;
  section?: 'personal' | 'shared' | 'sharedWithMe';
}

export const fileManagerApi = {

  createFolder: async ({ parentFolderId, folderName, section }: CreateFolderParams) => {
    try {
      const endpoint = section === 'personal' 
        ? '/api/documents/personal/folder'
        : '/api/documents/shared/folder';

      const params = new URLSearchParams();
      if (parentFolderId) params.append('parentFolderId', parentFolderId.toString());
      params.append('folderName', folderName);
      if (section === 'shared') {
        const email = localStorage.getItem('email');
        if (!email) {
          throw new Error('No email found in localStorage');
        }
        const userData = await getUserByEmail(email);
        params.append('ownerId', userData.id.toString());
        
        const agencyId = localStorage.getItem('selectedAgency');
        if (!agencyId) {
          throw new Error('No agencyId found in localStorage');
        }
        params.append('agencyId', agencyId);
      }

      const response = await axiosInstance.post(`${endpoint}?${params.toString()}`);
      return response.data;
    } catch (error) {
      console.error('Error creating folder:', error);
      throw new Error('Failed to create folder');
    }
  },

  getAllDocuments: async (userId: number, agencyId: number, documentStatus: any) => {
    try {
      const response = await axiosInstance.get('/api/file/all', {
        params: {
          userId,
          agencyId,
          documentStatus
        }
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      throw error;
    }
  },
  renameDocument: async (uniqueId: string, newName: string) => {
    try {
      const response = await axiosInstance.put('/api/file/rename', null, {
        params: {
          uniqueId,
          newName,
        },
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      throw error;
    }
  },
  moveDocument: async (userOwner: number, sourcePath: string | undefined, destinationPath: string) => {
    try {
      
      const normalizedSourcePath = sourcePath?.replace(/\//g, '\\').trim();
      const normalizedDestinationPath = destinationPath.replace(/\//g, '\\').trim();
      const response = await axiosInstance.put(
        '/api/file/move-folder',
        null,
        {
          params: {
            userOwner,
            sourcePath: normalizedSourcePath,
            destinationPath: normalizedDestinationPath,
          },
        }
      );
      return response.data;
    } catch (error) {
    
      throw error;
    }
  },
  
  unmarkAsFavorite: async (uniqueId: string) => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }
      const userData = await getUserByEmail(email);

      const response = await axiosInstance.put('/api/file/unmark-as-favorite', null, {
        params: {
          uniqueId,
          userId: userData.id
        }
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      throw error;
    }
  },
  markAsFavorite: async (uniqueId: string) => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }
      const userData = await getUserByEmail(email);
      
      const response = await axiosInstance.put('/api/file/mark-favorite', null, {
        params: {
          uniqueId,
          userId: userData.id
        }
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      throw error;
    }
  },
  deleteDocuments: async (userOwner: number, paths: string[]) => {
    try {
      const normalizedPaths = paths.map(path => {
        if (!path) return '';
        return path
          .replace(/\//g, '\\') 
          .replace(/\\\\/g, '\\') 
          .trim();
      }).filter(path => path); 
  
      const response = await axiosInstance.delete('/api/file/delete-documents', {
        data: {
          userOwner,
          paths: normalizedPaths
        }
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', error);
      throw error;
    }
  },
  getFolderContents: async (folderId: number) => {
    try {
    
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found');
      }
      const userData = await getUserByEmail(email);
  
      const params: any = {
        folderId,
        ownerId: userData.id
      };

      const agencyId = localStorage.getItem('selectedAgency');
      if (agencyId) {
        params.agencyId = agencyId;
      }
  
      const response = await axiosInstance.get('/api/file/document-contents', {
        params
      });
      return response.data;
    } catch (error: any) {
      console.error('API Error:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      
      if (error.response?.status === 404) {
        return [];
      }
      throw error;
    }
  },
  createCopy: async (uniqueId : string, destinationPath : string) => {
    try {
      const email = localStorage.getItem('email');
      if (!email) {
        throw new Error('No email found in localStorage');
      }
      const userData = await getUserByEmail(email);
  
  
      const response = await axiosInstance.post('/api/file/create-copy', null, {
        params: {
          uniqueId,
          destinationPath,
          userOwner: userData.id,
        }
      });
  
      return response.data;
    } catch (error) {
      console.error('API Error:');
      throw error;
    }
  },
  downloadElement: async (uniqueId: string, fileName: string) => {
    try {
        const response = await axiosInstance.get('/api/file/download-document', {
            params: { uniqueId },
            responseType: 'blob',
        });

        const contentType = response.headers['content-type'];
       
        let fileNameToDownload = fileName;

        if (!/\.[^.]+$/.test(fileNameToDownload)) {
            fileNameToDownload += '.zip';
        }

        const blob = new Blob([response.data], { type: contentType });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileNameToDownload);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('API Error:', error);
        throw error;
    }
},

shareDocument: async (uniqueId: string, recipientEmail: string, accessLevel: AccessLevel) => {
  try {
    const response = await axiosInstance.post('/api/file/share', null, {
      params: {
        uniqueId,
        recipientEmail,
        accessLevel
      }
    });
    return response.data;
  } catch (error: any) {
    console.error('API Error:', error);
    throw error;
  }
},

getSharedDocument: async (uniqueId: string, token: string) => {
  try {
    const response = await axiosInstance.get('/api/file/shared', {
      params: {
        uniqueId,
        token
      }
    });
    return response.data;
  } catch (error: any) {
    console.error('API Error:', error);
    throw error;
  }
},
getSharedWithMeDocuments: async () => {
  try {
    const email = localStorage.getItem('email');
    if (!email) {
      throw new Error('No email found ');
    }
    const userData = await getUserByEmail(email);

    const response = await axiosInstance.get('/api/file/shared-with-me', {
      params: {
        userId: userData.id,
      },
    });
    return response.data;
  } catch (error: any) {
    console.error('API Error:', error);
    throw error;
  }
},

getSharedDocuments: async (agencyId: number) => {
  try {
    if (!agencyId) {
      throw new Error('Agency ID is required');
    }

    const response = await axiosInstance.get('/api/file/shared-Documents', {
      params: {
        agencyId, 
      },
    });

    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
    });
    throw error;
  }
},




getPersonalDocuments: async () => {
  try {
    const email = localStorage.getItem('email');
    if (!email) {
      throw new Error('No email found ');
    }
    const userData = await getUserByEmail(email);
    const response = await axiosInstance.get('/api/file/personal', {
      params: {
        userId: userData.id
      }
    });
       
    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      config: error.config 
    });
    throw error;
  }
},

createPrivateFolder: async (
  folderName: string,
  parentFolderId?: number | null,
) => {
  try {
    const email = localStorage.getItem('email');
    if (!email) {
      throw new Error('No email found in localStorage');
    }
    const userData = await getUserByEmail(email);

    const response = await axiosInstance.post(
      `/api/file/create-private-folder`,
      null,
      {
        params: {
          folderName,
          parentFolderId,
          ownerId: userData.id,
        },
      }
    );

    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });
    throw error;
  }
},

createSharedFolder: async (
  folderName: string,
  parentFolderId?: number | null,

) => {
  try {
    const email = localStorage.getItem('email');
    if (!email) {
      throw new Error('No email found in localStorage');
    }
    const userData = await getUserByEmail(email);

    const agencyId = localStorage.getItem('selectedAgency');
    if (!agencyId) {
      throw new Error('No agencyId found in localStorage');
    }

    const response = await axiosInstance.post(
      `/api/file/create-shared-folder`,
      null,
      {
        params: {
          folderName,
          parentFolderId,
          ownerId: userData.id,
          agencyId,
     
        },
      }
    );

    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });
    throw error;
  }
},
generateShareLink: async (uniqueId: string) => {
  try {
    const response = await axiosInstance.get('/api/file/generate-share-link', {
      params: {
        uniqueId
      }
    });
    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });
    throw error;
  }
},

uploadFile: async ({ file, section}: UploadParams) => {
  try {
    const email = localStorage.getItem('email');
    if (!email) {
      throw new Error('No email');
    }
    const userData = await getUserByEmail(email);

    const formData = new FormData();
    formData.append('file', file);
    formData.append('userOwner', userData.id);
    
    

    let endpoint = '';
    if (section === 'personal') {
      endpoint = '/api/file/upload-personal';
    } else if (section === 'shared') {
      const agencyId = localStorage.getItem('selectedAgency');
      if (!agencyId) {
        throw new Error('no agencyId');
      }
      formData.append('agencyId', agencyId);
      endpoint = '/api/file/upload-shared';
    }

    const response = await axiosInstance.post(endpoint, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data;
  } catch (error: any) {
    console.error('Upload error:', error);
    throw error;
  }
},
getFileUrl: async (name: string) => {
  try {
    const response = await axiosInstance.get('/api/file/url', {
      params: { name }
    });
    return response.data;
  } catch (error: any) {
    console.error('API Error:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });
    throw error;
  }
},
};
