import { CenterItem } from '@/types'
import { resolveMediaUrl } from '@/services/shared/media-url'

const API_BASE = (process.env.NEXT_PUBLIC_AAU_API_BASE_URL || process.env.AAU_API_BASE_URL || 'https://edu.yemenfrappe.com').replace(/\/$/, '')
const CENTERS_LIST_ENDPOINT = '/api/centers'
const CENTERS_DETAIL_ENDPOINT = '/api/centers'

async function fetchCentersJson(path: string) {
  const response = await fetch(`${API_BASE}${path}`, {
    headers: { Accept: 'application/json' },
    cache: 'no-store',
  })

  if (!response.ok) {
    throw new Error(`Centers API request failed: ${response.status}`)
  }

  return response.json()
}

function unwrapCentersPayload(payload: any) {
  if (payload?.ok === true) {
    return payload.data
  }
  if (payload?.data?.ok === true) {
    return payload.data.data
  }
  if (payload?.data !== undefined) {
    return payload.data
  }
  return payload
}

function pickText(item: any, keys: string[], fallback = ''): string {
  for (const key of keys) {
    const value = item?.[key]
    if (value !== undefined && value !== null && String(value).trim()) {
      return String(value)
    }
  }
  return fallback
}

function normalizeLocalizedList(arValue: any, enValue: any) {
  const parse = (value: any): string[] => {
    if (Array.isArray(value)) {
      return value
        .map((entry: any) => String(entry?.value || entry || '').trim())
        .filter(Boolean)
    }
    if (typeof value === 'string') {
      return value
        .split('\n')
        .map((entry) => entry.trim())
        .filter(Boolean)
    }
    return []
  }

  if (Array.isArray(arValue) && arValue.some((entry: any) => typeof entry === 'object' && (entry?.ar || entry?.en))) {
    return arValue.map((entry: any) => {
      const ar = String(entry?.ar || entry?.value || '')
      const en = String(entry?.en || '')
      return { ar, en }
    })
  }

  const arItems = parse(arValue)
  const enItems = parse(enValue)
  const total = Math.max(arItems.length, enItems.length)
  return Array.from({ length: total }, (_, idx) => {
    const ar = arItems[idx] || enItems[idx] || ''
    const en = enItems[idx] || ''
    return { ar, en }
  }).filter((entry) => entry.ar)
}

function mapCenterItem(item: any): CenterItem {
  const locationAr = pickText(item, ['locationAr', 'location', 'location_ar'])
  const locationEn = pickText(item, ['locationEn', 'location_en'], '')
  return {
    id: pickText(item, ['id'], ''),
    titleAr: pickText(item, ['titleAr', 'title_ar', 'title'], ''),
    titleEn: pickText(item, ['titleEn', 'title_en'], ''),
    descAr: pickText(item, ['descAr', 'desc_ar', 'descriptionAr', 'description_ar', 'description'], ''),
    descEn: pickText(item, ['descEn', 'desc_en', 'descriptionEn', 'description_en'], ''),
    services: normalizeLocalizedList(item?.services, item?.services_en || item?.servicesEn),
    programs: normalizeLocalizedList(item?.programs, item?.programs_en || item?.programsEn),
    image: resolveMediaUrl(item?.image),
    location: locationAr,
    locationAr,
    locationEn,
    phone: pickText(item, ['phone'], ''),
    email: pickText(item, ['email'], ''),
  }
}

export async function getCentersList(): Promise<CenterItem[]> {
  try {
    const payload = await fetchCentersJson(CENTERS_LIST_ENDPOINT)
    const data = unwrapCentersPayload(payload)
    const items = Array.isArray(data) ? data : Array.isArray(payload) ? payload : []
    return items.map(mapCenterItem)
  } catch {
    return []
  }
}

export async function getCenterById(id: string): Promise<CenterItem | null> {
  try {
    const payload = await fetchCentersJson(`${CENTERS_DETAIL_ENDPOINT}/${encodeURIComponent(id)}`)
    const data = unwrapCentersPayload(payload)
    return mapCenterItem(data)
  } catch {
    try {
      const list = await getCentersList()
      const normalized = decodeURIComponent(String(id || '')).trim().toLowerCase()
      return (
        list.find((item) => String(item.id || '').trim().toLowerCase() === normalized) || null
      )
    } catch {
      return null
    }
  }
}
