import API_CONFIG from '../config/api';
import { toFrappeFilterArray } from '../utils/listFilterUtils';

// Support Plan interfaces
export interface SupportPlan {
  name: string;
  owner: string;
  creation: string;
  modified: string;
  modified_by: string;
  docstatus: number;
  idx: number;
  support_plan: string;
  frequency: string;
  max_downtime_hrs: number;
  asset: string | null;
  starting_date: string | null;
  penalty_factor: number;
  custom_contractwarranty: string;
  custom_contract_value: string;
  warranty: number;
  warranty_start_date: string | null;
  warranty_end_date: string | null;
  war_status: string;
  extended_warranty: number;
  start: string | null;
  end: string | null;
  service_contract: number;
  spare_parts: number;
  spare_parts_labour: number;
  labour: number;
  ppm_only: number;
  no: number;
  start_date: string | null;
  end_date: string | null;
  service_contract_status: string;
  vendor: string | null;
  asset_list: any[];
}

export interface CreateSupportPlanData {
  support_plan?: string;
  frequency?: string;
  max_downtime_hrs?: number;
  asset?: string | null;
  starting_date?: string | null;
  penalty_factor?: number;
  custom_contractwarranty?: string;
  custom_contract_value?: string;
  warranty?: number;
  warranty_start_date?: string | null;
  warranty_end_date?: string | null;
  war_status?: string;
  extended_warranty?: number;
  start?: string | null;
  end?: string | null;
  service_contract?: number;
  spare_parts?: number;
  spare_parts_labour?: number;
  labour?: number;
  ppm_only?: number;
  no?: number;
  start_date?: string | null;
  end_date?: string | null;
  service_contract_status?: string;
  vendor?: string | null;
  asset_list?: any[];
}

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

export interface SupportPlanListResponse {
  data: SupportPlan[];
  total_count?: number;
}

class SupportPlanService {
  private baseURL: string;

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

  // Get CSRF Token
  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;
    }
  }

  // Get headers with CSRF token
  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 support plans
  async getSupportPlans(params: SupportPlanListParams = {}): Promise<SupportPlanListResponse> {
    const {
      filters = {},
      fields = [
        'name', 'support_plan', 'frequency', 'max_downtime_hrs', 'asset',
        'starting_date', 'penalty_factor', 'custom_contractwarranty',
        'custom_contract_value', 'warranty', 'warranty_start_date',
        'warranty_end_date', 'war_status', 'extended_warranty',
        'service_contract', 'spare_parts', 'spare_parts_labour',
        'labour', 'ppm_only', 'start_date', 'end_date',
        'service_contract_status', 'vendor',
        'creation', 'modified', 'owner', 'modified_by', 'docstatus'
      ],
      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 = toFrappeFilterArray(filters);
      if (filterArray.length > 0) queryParams.append('filters', JSON.stringify(filterArray));
    }

    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans?${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 support plan details
  async getSupportPlan(name: string): Promise<SupportPlan> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans/${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 support plan
  async createSupportPlan(data: CreateSupportPlanData): Promise<SupportPlan> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans`,
      {
        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 support plan
  async updateSupportPlan(name: string, data: Partial<CreateSupportPlanData>): Promise<SupportPlan> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans/${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 support plan
  async deleteSupportPlan(name: string): Promise<void> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans/${encodeURIComponent(name)}`,
      {
        method: 'DELETE',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

  // Get support plan count
  async getSupportPlanCount(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 = toFrappeFilterArray(filters);
      if (filterArray.length > 0) queryParams.append('filters', JSON.stringify(filterArray));
    }

    const response = await fetch(
      `${this.baseURL}/api/resource/Support Plans?${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;
  }

  // Get current user
  async getCurrentUser(): Promise<string> {
    try {
      const response = await fetch(
        `${this.baseURL}/api/method/frappe.auth.get_logged_user`,
        {
          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.message || '';
    } catch (error) {
      console.error('Error getting current user:', error);
      return '';
    }
  }
}

const supportPlanService = new SupportPlanService();
export default supportPlanService;