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

// Inspection interfaces
export interface Inspection {
  attachment_on_close: string;
  extension_no: string;
  attachment: string;
  assigned_technician: string;
  location: string;
  department: string;
  work_order_type: string;
  name: string;
  owner: string;
  creation: string;
  modified: string;
  modified_by: string;
  docstatus: number;
  idx: number;
  workflow_state: string;
  inspection_type: string;
  status: string;
  inspection_date?: string;
  target_closure_date?: string;
  requested_by?: string;
  technician_department?: string;
  linked_corrective_wo_no?: string;
  observation_note?: string;
  technical_response?: string;
  custom_delete_status?: string;
}

export interface CreateInspectionData {
  extension_no: string;
  attachment: string;
  assigned_technician: string;
  location: string;
  department: string;
  work_order_type: string
  inspection_type?: string;
  status?: string;
  inspection_date?: string;
  target_closure_date?: string;
  requested_by?: string;
  technician_department?: string;
  linked_corrective_wo_no?: string;
  observation_note?: string;
  technical_response?: string;
  workflow_state?: string;
  docstatus?: number;
}

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

export interface InspectionListResponse {
  data: Inspection[];
  total_count?: number;
}

class InspectionService {
  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 inspections
  async getInspections(params: InspectionListParams = {}): Promise<InspectionListResponse> {
    const {
      filters = {},
      fields = [
        'name', 'workflow_state', 'inspection_type', 'status', 
        'inspection_date', 'target_closure_date', 'requested_by',
        'technician_department', 'linked_corrective_wo_no',
        'observation_note', 'technical_response',
        'creation', 'modified', 'owner', 'modified_by', 'custom_delete_status'
      ],
      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/Inspection?${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 inspection details
  async getInspection(name: string): Promise<Inspection> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Inspection/${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 inspection
  async createInspection(data: CreateInspectionData): Promise<Inspection> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Inspection`,
      {
        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 inspection
  async updateInspection(name: string, data: Partial<CreateInspectionData>): Promise<Inspection> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Inspection/${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 inspection
  async deleteInspection(name: string): Promise<void> {
    const response = await fetch(
      `${this.baseURL}/api/resource/Inspection/${encodeURIComponent(name)}`,
      {
        method: 'DELETE',
        headers: await this.getHeaders(),
        credentials: 'include',
      }
    );

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

  // Get inspection count
  async getInspectionCount(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/Inspection?${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 (for auto-populating requested_by)
  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 inspectionService = new InspectionService();
export default inspectionService;