import { ProjectDetails, ProjectDocument, SimilarProject, ApiResponse } from '@/types/project-details';

const API_BASE_URL = typeof window !== 'undefined' 
  ? '' // Use relative URL on client-side
  : process.env.NEXT_PUBLIC_APP_URL || 'http://46.202.162.227:3003';

export async function fetchProjectDetails(projectId: string): Promise<ProjectDetails> {
  try {
    const url = `${API_BASE_URL}/api/projects/${projectId}/details`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      cache: 'no-store', // Always fetch fresh data
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! status: ${response.status} - ${errorText}`);
    }

    const result: ApiResponse<ProjectDetails> = await response.json();
    
    if (!result.success) {
      throw new Error(result.error || 'Failed to fetch project details');
    }

    return result.data;
  } catch (error) {
    console.error('Error fetching project details:', error);
    throw error;
  }
}

export async function fetchProjectDocuments(projectId: string): Promise<ProjectDocument[]> {
  try {
    const response = await fetch(`${API_BASE_URL}/api/projects/${projectId}/documents`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      cache: 'no-store',
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result: ApiResponse<ProjectDocument[]> = await response.json();
    
    if (!result.success) {
      throw new Error(result.error || 'Failed to fetch project documents');
    }

    return result.data;
  } catch (error) {
    console.error('Error fetching project documents:', error);
    throw error;
  }
}

export async function fetchSimilarProjects(
  categoryId?: string, 
  limit: number = 6,
  excludeProjectId?: string,
  datacounter?:any
): Promise<SimilarProject[]> {
  try {
    const params = new URLSearchParams({
      limit: limit.toString(),
      sortBy: 'newest',
    });

    if (categoryId) {
      params.append('categoryId', categoryId);
    }
    if (datacounter) {
      params.append('countryId', datacounter);
    }

    if (excludeProjectId) {
      params.append('exclude', excludeProjectId);
    }

    const response = await fetch(`${API_BASE_URL}/api/projects?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      cache: 'no-store',
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result: ApiResponse<{ projects: any[], total: number }> = await response.json();
    
    if (!result.success) {
      throw new Error(result.error || 'Failed to fetch similar projects');
    }

    // console.log("result result.data.projects ======", result.data.projects)

    // Transform the projects data to match SimilarProject interface
    const similarProjects: SimilarProject[] = result.data.projects.slice(0, 2).map(project => ({
      id: project.id,
      title: project.title,
      description: project.description,
      budget: project.budget,
      currency: project.currency || 'EUR',
      category: project.category?.name || 'General',
      categoryIcon: project.category?.icon || '/assets/image/category/default.svg',
      clientName: project.client?.name || 'Unknown Client',
      clientAvatar: project.client?.profileImage || '/assets/image/user.png',
      clientRating: project.client?.rating || 4.5,
      clientReviewsCount: project.client?.reviewCount || 0,
      bidsCount: project.bidsCount || 0,
      duration: project.duration || 15,
      status: project.status || 'active'
    }));

    return similarProjects;
  } catch (error) {
    console.error('Error fetching similar projects:', error);
    // Return empty array on error to avoid breaking the UI
    return [];
  }
}

export function getDocumentIcon(type: string): string {
  const iconMap: { [key: string]: string } = {
    // PDF files
    'pdf': '/assets/image/pdf.svg',
    'application/pdf': '/assets/image/pdf.svg',
    
    // Image files
    'png': '/assets/image/png.svg',
    'image/png': '/assets/image/png.svg',
    'jpg': '/assets/image/png.svg',
    'jpeg': '/assets/image/png.svg',
    'image/jpeg': '/assets/image/png.svg',
    'image/jpg': '/assets/image/png.svg',
    'gif': '/assets/image/png.svg',
    'image/gif': '/assets/image/png.svg',
    'svg': '/assets/image/svg.svg',
    'image/svg+xml': '/assets/image/svg.svg',
    
    // Document files
    'doc': '/assets/image/document-text.svg',
    'docx': '/assets/image/document-text.svg',
    'application/msword': '/assets/image/document-text.svg',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '/assets/image/document-text.svg',
    
    // Spreadsheet files
    'xls': '/assets/image/document-text.svg',
    'xlsx': '/assets/image/document-text.svg',
    'csv': '/assets/image/document-text.svg',
    'application/vnd.ms-excel': '/assets/image/document-text.svg',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '/assets/image/document-text.svg',
    'text/csv': '/assets/image/document-text.svg',
    'application/csv': '/assets/image/document-text.svg',
    
    // Video files
    'mp4': '/assets/image/vid.svg',
    'video/mp4': '/assets/image/vid.svg',
    'avi': '/assets/image/vid.svg',
    'video/avi': '/assets/image/vid.svg',
    'mov': '/assets/image/vid.svg',
    'video/mov': '/assets/image/vid.svg',
    'video': '/assets/image/vid.svg',
  };

  return iconMap[type.toLowerCase()] || '/assets/image/document-text.svg';
}

export function getDocumentIconBackground(type: string): string {
  const backgroundMap: { [key: string]: string } = {
    // PDF files - Red background
    'pdf': '#FEE2E2',
    'application/pdf': '#FEE2E2',
    
    // Image files - Orange background  
    'png': '#FCE3CF',
    'image/png': '#FCE3CF',
    'jpg': '#FCE3CF',
    'jpeg': '#FCE3CF',
    'image/jpeg': '#FCE3CF',
    'image/jpg': '#FCE3CF',
    'gif': '#FCE3CF',
    'image/gif': '#FCE3CF',
    'svg': '#E2EEFE',
    'image/svg+xml': '#E2EEFE',
    
    // Document files - Blue background
    'doc': '#E2F4FD',
    'docx': '#E2F4FD',
    'application/msword': '#E2F4FD',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '#E2F4FD',
    
    // Spreadsheet files - Green background
    'xls': '#E8F5E8',
    'xlsx': '#E8F5E8',
    'csv': '#E8F5E8',
    'application/vnd.ms-excel': '#E8F5E8',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '#E8F5E8',
    'text/csv': '#E8F5E8',
    'application/csv': '#E8F5E8',
    
    // Video files - Purple background
    'mp4': '#E5E2FE',
    'video/mp4': '#E5E2FE',
    'avi': '#E5E2FE',
    'video/avi': '#E5E2FE',
    'mov': '#E5E2FE',
    'video/mov': '#E5E2FE',
    'video': '#E5E2FE',
  };

  return backgroundMap[type.toLowerCase()] || '#ffe5db';
}

export function detectFileTypeFromUrl(url: string, filename?: string): string {
  // Get file extension from URL or filename
  const source = filename || url;
  const extension = source.split('.').pop()?.toLowerCase();
  
  if (!extension) {
    return 'unknown';
  }
  
  // Map extensions to MIME types
  const extensionToMimeType: { [key: string]: string } = {
    // Images
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg', 
    'png': 'image/png',
    'gif': 'image/gif',
    'svg': 'image/svg+xml',
    
    // Documents
    'pdf': 'application/pdf',
    'doc': 'application/msword',
    'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    
    // Spreadsheets
    'xls': 'application/vnd.ms-excel',
    'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'csv': 'text/csv',
    
    // Videos
    'mp4': 'video/mp4',
    'avi': 'video/avi',
    'mov': 'video/mov'
  };
  
  return extensionToMimeType[extension] || extension;
}