interface ApiResponse<T = unknown> {
  success: boolean
  data?: T
  error?: string
  message?: string
  pagination?: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

class ApiClient {
  private baseUrl: string

  constructor() {
    this.baseUrl = '/api'
  }

  private getHeaders(): HeadersInit {
    const headers: HeadersInit = { 'Content-Type': 'application/json' }
    if (typeof window !== 'undefined') {
      const token = localStorage.getItem('isp_token')
      if (token) headers['x-user-id'] = token
    }
    return headers
  }

  private buildUrl(url: string, params?: Record<string, string | number | boolean | undefined | null>): string {
    const fullUrl = `${this.baseUrl}${url}`
    if (!params) return fullUrl

    const searchParams = new URLSearchParams()
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value))
      }
    })

    const qs = searchParams.toString()
    return qs ? `${fullUrl}?${qs}` : fullUrl
  }

  async get<T = unknown>(url: string, params?: Record<string, string | number | boolean | undefined | null>): Promise<ApiResponse<T>> {
    try {
      const fullUrl = this.buildUrl(url, params)
      const res = await fetch(fullUrl, { method: 'GET', headers: this.getHeaders() })
      const data = await res.json()
      return data as ApiResponse<T>
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Network error'
      return { success: false, error: message }
    }
  }

  async post<T = unknown>(url: string, body?: unknown): Promise<ApiResponse<T>> {
    try {
      const res = await fetch(`${this.baseUrl}${url}`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: body ? JSON.stringify(body) : undefined,
      })
      const data = await res.json()
      return data as ApiResponse<T>
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Network error'
      return { success: false, error: message }
    }
  }

  async put<T = unknown>(url: string, body?: unknown): Promise<ApiResponse<T>> {
    try {
      const res = await fetch(`${this.baseUrl}${url}`, {
        method: 'PUT',
        headers: this.getHeaders(),
        body: body ? JSON.stringify(body) : undefined,
      })
      const data = await res.json()
      return data as ApiResponse<T>
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Network error'
      return { success: false, error: message }
    }
  }

  async del<T = unknown>(url: string): Promise<ApiResponse<T>> {
    try {
      const res = await fetch(`${this.baseUrl}${url}`, {
        method: 'DELETE',
        headers: this.getHeaders(),
      })
      const data = await res.json()
      return data as ApiResponse<T>
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Network error'
      return { success: false, error: message }
    }
  }
}

export const api = new ApiClient()
export type { ApiResponse }
