import API_CONFIG from '../config/api';

// Maintenance Team Member interface
export interface MaintenanceTeamMember {
  name?: string;
  team_member: string;
  full_name?: string;
  maintenance_role?: string;
  idx?: number;
}

// Maintenance Team interface
export interface MaintenanceTeam {
  name: string;
  owner?: string;
  creation?: string;
  modified?: string;
  modified_by?: string;
  docstatus?: number;
  maintenance_team_name: string;
  maintenance_manager?: string;
  maintenance_manager_name?: string;
  company?: string;
  custom_expertise?: string;
  maintenance_team_members?: MaintenanceTeamMember[];
}

export interface CreateMaintenanceTeamData {
  maintenance_team_name: string;
  maintenance_manager?: string;
  maintenance_manager_name?: string;
  company?: string;
  custom_expertise?: string;
  maintenance_team_members?: MaintenanceTeamMember[];
}

export interface MaintenanceTeamListParams {
  filters?: Record<string, any>;
  fields?: string[];
  limit_start?: number;
  limit_page_length?: number;
  order_by?: string;
}

export interface MaintenanceTeamListResponse {
  data: MaintenanceTeam[];
  total_count?: number;
}

class MaintenanceTeamService {
  private baseURL: string;

  constructor() {
    this.baseURL = API_CONFIG.BASE_URL;
  }

  private async getCSRFToken(): Promise<string | null> {
    try {
      if (typeof window !== 'undefined' && (window as any).csrf_token) {
        return (window as any).csrf_token;
      }
      return null;
    } catch (error) {
      return null;
    }
  }

  private async getHeaders(): Promise<Record<string, string>> {
    const headers: Record<string, string> = {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    };

    const csrfToken = await this.getCSRFToken();
    if (csrfToken) {
      headers['X-Frappe-CSRF-Token'] = csrfToken;
    }

    return headers;
  }

  // Get list of maintenance teams
  async getMaintenanceTeams(params: MaintenanceTeamListParams = {}): Promise<MaintenanceTeamListResponse> {
    const {
      filters = {},
      fields = ['name', 'maintenance_team_name', 'maintenance_manager', 'maintenance_manager_name', 'company', 'custom_expertise', 'creation', 'modified'],
      limit_start = 0,
      limit_page_length = 20,
      order_by = 'creation desc',
    } = params;

    const queryParams = new URLSearchParams();
    queryParams.append('fields', JSON.stringify(fields));
    queryParams.append('limit_start', limit_start.toString());
    queryParams.append('limit_page_length', limit_page_length.toString());
    queryParams.append('order_by', order_by);

    if (Object.keys(filters).length > 0) {
      const filterArray = Object.entries(filters).map(([key, value]) => [key, '=', value]);
      queryParams.append('filters', JSON.stringify(filterArray));
    }

    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team?${queryParams.toString()}`,
      {
        method: 'GET',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

    const result = await response.json();
    return { data: result.data || [] };
  }

  // Get single maintenance team details
  async getMaintenanceTeam(name: string): Promise<MaintenanceTeam> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team/${encodeURIComponent(name)}`,
      {
        method: 'GET',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

    const result = await response.json();
    return result.data;
  }

  // Create new maintenance team
  async createMaintenanceTeam(data: CreateMaintenanceTeamData): Promise<MaintenanceTeam> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team`,
      {
        method: 'POST',
        headers: await this.getHeaders(),
        credentials: 'include',
        body: JSON.stringify(data),
      }
    );

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result.data;
  }

  // Update maintenance team
  async updateMaintenanceTeam(name: string, data: Partial<CreateMaintenanceTeamData>): Promise<MaintenanceTeam> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team/${encodeURIComponent(name)}`,
      {
        method: 'PUT',
        headers: await this.getHeaders(),
        credentials: 'include',
        body: JSON.stringify(data),
      }
    );

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result.data;
  }

  // Delete maintenance team
  async deleteMaintenanceTeam(name: string): Promise<void> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team/${encodeURIComponent(name)}`,
      {
        method: 'DELETE',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

  // Get maintenance team count
  async getMaintenanceTeamCount(filters: Record<string, any> = {}): Promise<number> {
    const queryParams = new URLSearchParams();
    queryParams.append('fields', JSON.stringify(['count(name) as count']));

    if (Object.keys(filters).length > 0) {
      const filterArray = Object.entries(filters).map(([key, value]) => [key, '=', value]);
      queryParams.append('filters', JSON.stringify(filterArray));
    }

    const response = await fetch(
      `${this.baseURL}/api/resource/Asset Maintenance Team?${queryParams.toString()}`,
      {
        method: 'GET',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

    const result = await response.json();
    return result.data?.[0]?.count || 0;
  }

  // Fetch user full name for maintenance manager
  async getUserFullName(email: string): Promise<string> {
    try {
      const response = await fetch(
        `${this.baseURL}/api/resource/User/${encodeURIComponent(email)}?fields=["full_name"]`,
        {
          method: 'GET',
          headers: await this.getHeaders(),
          credentials: 'include',
        }
      );

      if (!response.ok) return '';

      const result = await response.json();
      return result.data?.full_name || '';
    } catch {
      return '';
    }
  }
}

const maintenanceTeamService = new MaintenanceTeamService();
export default maintenanceTeamService;