import { CenterItem } from '@/types'

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

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

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

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

  const parseLines = (value: any) => {
    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 []
  }

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

function mapCenter(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: normalizeLocalizedListPair(item?.services, item?.servicesEn || item?.services_en),
    programs: normalizeLocalizedListPair(item?.programs, item?.programsEn || item?.programs_en),
    image: item?.image || '',
    location: locationAr,
    locationAr,
    locationEn,
    phone: pickText(item, ['phone'], ''),
    email: pickText(item, ['email'], ''),
  }
}

async function fetchCenters(): Promise<CenterItem[]> {
  try {
    const response = await fetch(`${API_BASE}/api/centers`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    })

    if (!response.ok) {
      return []
    }

    const payload = await response.json()
    const data = unwrapEntityPayload(payload)
    const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : []
    return items.map(mapCenter)
  } catch {
    return []
  }
}

export const centersService = {
  getAll: fetchCenters,

  getById: async (id: string): Promise<CenterItem | null> => {
    try {
      const response = await fetch(`${API_BASE}/api/centers/${encodeURIComponent(id)}`, {
        headers: { Accept: 'application/json' },
        cache: 'no-store',
      })

      if (!response.ok) {
        return null
      }

      const payload = await response.json()
      return mapCenter(unwrapEntityPayload(payload))
    } catch {
      return null
    }
  },
}
