// lib/facultyData.ts

export interface TeamMember {
  id: number;
  professorId: string;
  name: string;
  firstName: string;
  lastName: string;
  position: string;
  designation: string;
  image: string;
  profileUrl?: string;
  phone: string;
  email: string;
  experience: string;
  description: string;
  specialty: string;
  certification: string;
  training: string;
  workDays: string[];
  skills: Skill[];
  awards: Award[];
  status?: string;
  department?: string;
  officeLocation?: string;
  joinDate?: string;
  category: string;
}

export interface Skill {
  name: string;
  level?: number;
}

export interface Award {
  title: string;
  year: string;
  description: string;
  image: string;
}

export interface FacultyApiResponse {
  content: TeamMember[];
  last: boolean;
  first: boolean;
  totalElements: number;
  size: number;
  numberOfElements: number;
  number: number;
  empty: boolean;
}

// API service class
export class FacultyService {
  private static baseUrl =
    process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';

  static async getAllFaculty(): Promise<TeamMember[]> {
    try {
      const response = await fetch(`${this.baseUrl}/professor?size=100`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      });

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

      const data: FacultyApiResponse = await response.json();
      return this.transformProfessorsToTeamMembers(data.content);
    } catch (error) {
      console.error('Error fetching faculty data:', error);
      return this.getFallbackData();
    }
  }

  // ✅ FIXED: Now accepts both numeric ID and UUID professorId
  static async getFacultyById(id: number | string): Promise<TeamMember | null> {
    try {
      // If it's a UUID (string with dashes), fetch directly from API
      if (typeof id === 'string' && id.includes('-')) {
        return await this.getFacultyByProfessorId(id);
      }

      // Otherwise, fetch all and find by numeric ID
      const allFaculty = await this.getAllFaculty();
      return allFaculty.find(member => member.id === id) || null;
    } catch (error) {
      console.error('Error fetching faculty member:', error);
      return null;
    }
  }

  static async getFacultyByProfessorId(professorId: string): Promise<TeamMember | null> {
    try {
      const response = await fetch(`${this.baseUrl}/professor/${professorId}`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      });

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

      const professor = await response.json();
      const transformed = this.transformProfessorsToTeamMembers([professor]);
      return transformed[0] || null;
    } catch (error) {
      console.error('Error fetching professor by ID:', error);
      return null;
    }
  }

  static async getFacultyByCategory(category: string): Promise<TeamMember[]> {
    try {
      const allFaculty = await this.getAllFaculty();
      return allFaculty.filter(member => member.category === category);
    } catch (error) {
      console.error('Error fetching faculty by category:', error);
      return [];
    }
  }

  // Helper method to check if an image URL is accessible
  static async checkImageExists(imageUrl: string): Promise<boolean> {
    try {
      const response = await fetch(imageUrl, { method: 'HEAD' });
      return response.ok;
    } catch (error) {
      return false;
    }
  }

  // Helper method to get a working image URL with fallback
  static async getWorkingImageUrl(originalUrl: string, fallbackUrl: string = '/images/default-avatar.jpg'): Promise<string> {
    const isAccessible = await this.checkImageExists(originalUrl);
    return isAccessible ? originalUrl : fallbackUrl;
  }

  private static transformProfessorsToTeamMembers(professors: any[]): TeamMember[] {
    return professors.map((prof, index) => {
      // Create proper image URL - remove /api from baseUrl for images
      const imageBaseUrl = this.baseUrl;
      let imageUrl = '/images/default-avatar.jpg'; // Default fallback

      if (prof.profileImageUrl) {
        // If it's already a full URL, use it as is
        if (prof.profileImageUrl.startsWith('http')) {
          imageUrl = prof.profileImageUrl;
          // ✅ FIX: Replace /user/ with /professor/ in the URL
          imageUrl = imageUrl.replace('/user/', '/professor/');
        } else {
          // If it's a relative URL, construct the full URL
          let relativePath = prof.profileImageUrl;
          // ✅ FIX: Replace /user/ with /professor/ in relative paths too
          relativePath = relativePath.replace('/user/', '/professor/');
          imageUrl = `${imageBaseUrl}${relativePath}`;
        }
      }

      return {
        id: index + 1, // Generate sequential ID for UI
        professorId: prof.professorId,
        name: prof.name || `${prof.firstName} ${prof.lastName}`,
        firstName: prof.firstName,
        lastName: prof.lastName,
        position: prof.position || 'Faculty Member',
        designation: prof.designation || prof.position || 'Faculty Member',
        image: imageUrl,
        // ✅ FIXED: Use professorId in URL instead of numeric ID
        profileUrl: `/faculty/${prof.professorId}`,
        phone: prof.phone || 'Not available',
        email: prof.email,
        experience: prof.experience || 'Not specified',
        description: prof.description || `${prof.firstName} ${prof.lastName} is a dedicated member of our faculty.`,
        specialty: prof.specialty || prof.department || 'General Medicine',
        certification: prof.certification || 'Medical certification details not available',
        training: prof.training || 'Professional training details not available',
        workDays: prof.workDays || ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
        skills: prof.skills?.map((skill: any) => ({
          name: skill.name,
          level: skill.level
        })) || [
            { name: 'Clinical Practice', level: 90 },
            { name: 'Research', level: 85 },
            { name: 'Teaching', level: 88 }
          ],
        awards: prof.awards?.map((award: any) => ({
          title: award.title,
          year: award.year,
          description: award.description,
          image: award.imageUrl || '/images/award-icon.png'
        })) || [
            {
              title: 'Excellence in Medical Practice',
              year: new Date().getFullYear().toString(),
              description: 'Recognized for outstanding contribution to medical practice and patient care.',
              image: '/images/award-icon.png'
            }
          ],
        status: prof.status,
        department: prof.department,
        officeLocation: prof.officeLocation,
        joinDate: prof.joinDate,
        category: prof.category || 'FACULTY'
      };
    });
  }

  private static getFallbackData(): TeamMember[] {
    return [
      {
        id: 1,
        professorId: 'fallback-1',
        name: "Loading Faculty Data...",
        firstName: "Loading",
        lastName: "Data",
        position: "Please wait while we fetch the latest faculty information",
        designation: "System Message",
        image: "/images/default-avatar.jpg",
        profileUrl: '/faculty/fallback-1',
        phone: "Not available",
        email: "support@institution.edu",
        experience: "N/A",
        description: "Faculty data is currently being loaded from the server.",
        specialty: "N/A",
        certification: "N/A",
        training: "N/A",
        workDays: [],
        skills: [],
        awards: [],
        category: 'FACULTY'
      }
    ];
  }
}

// Helper function to get team members (for backward compatibility)
export const getTeamMembers = async (): Promise<TeamMember[]> => {
  return await FacultyService.getAllFaculty();
};

// Helper function to get team member by ID (now accepts both numeric and UUID)
export const getTeamMemberById = async (id: number | string): Promise<TeamMember | null> => {
  return await FacultyService.getFacultyById(id);
};

// Helper function to get team member by professorId (UUID)
export const getTeamMemberByProfessorId = async (professorId: string): Promise<TeamMember | null> => {
  return await FacultyService.getFacultyByProfessorId(professorId);
};