'use client'

import type { AcademicProgram, College } from '@/types'
import { portalRequest } from './portal-api'

type CollegePayload = {
  college_name: string
  slug?: string
  name_ar?: string
  name_en?: string
  description?: string
  description_ar?: string
  description_en?: string
  vision_ar?: string
  vision_en?: string
  mission_ar?: string
  mission_en?: string
  goals_ar?: string
  goals_en?: string
  quality_ar?: string
  quality_en?: string
  values_ar?: string
  values_en?: string
  strategy_ar?: string
  strategy_en?: string
  image?: string
  background_image?: string
  icon?: string
  dean_name_ar?: string
  dean_name?: string
  dean_name_en?: string
  dean_image?: string
  is_active?: number
  display_order?: number
}

type ProgramPayload = {
  program_name: string
  name_ar?: string
  name_en?: string
  degree_type?: string
  description?: string
  description_ar?: string
  description_en?: string
  objectives_ar?: string
  objectives_en?: string
  career_prospects_ar?: string
  career_prospects_en?: string
  application_steps_ar?: string
  application_steps_en?: string
  why_program_ar?: string
  why_program_en?: string
  department_ar?: string
  department_en?: string
  admission_rate?: number
  high_school_type?: string
  high_school_type_en?: string
  study_years?: string
  image?: string
  duration?: string
  college: string
  is_active?: number
}

function safeString(value: any) {
  return String(value || '').trim()
}

function safeNumber(value: any) {
  const number = Number(value)
  return Number.isFinite(number) ? number : 0
}

function parseTextList(value: any): string[] {
  if (Array.isArray(value)) {
    return value.map((item) => safeString(item)).filter(Boolean)
  }
  const text = safeString(value)
  if (!text) return []
  return text
    .replace(/[;,،]+/g, '\n')
    .split('\n')
    .map((entry) => entry.trim())
    .filter(Boolean)
}

function parseProgramsJson(raw: any): AcademicProgram[] {
  if (!raw) return []
  try {
    const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
    if (!Array.isArray(parsed)) return []
    return parsed.map((item: any) => ({
      id: safeString(item?.id || item?.docname || item?.name || crypto.randomUUID?.() || Math.random().toString(36).slice(2)),
      nameAr: safeString(item?.nameAr || item?.programName || item?.program_name),
      nameEn: safeString(item?.nameEn || item?.programName || item?.program_name),
      departmentAr: safeString(item?.departmentAr || item?.department_ar),
      departmentEn: safeString(item?.departmentEn || item?.department_en),
      admissionRate: safeNumber(item?.admissionRate),
      highSchoolType: (item?.highSchoolType || 'علمي') as AcademicProgram['highSchoolType'],
      highSchoolTypeEn: (item?.highSchoolTypeEn || 'Scientific') as AcademicProgram['highSchoolTypeEn'],
      studyYears: safeString(item?.studyYears || item?.duration),
      image: item?.image || '',
      descriptionAr: safeString(item?.descriptionAr || item?.description),
      descriptionEn: safeString(item?.descriptionEn || item?.description),
      objectives: Array.isArray(item?.objectives) ? item.objectives : [],
      careerProspectsAr: parseTextList(item?.careerProspectsAr || item?.career_prospects_ar),
      careerProspectsEn: parseTextList(item?.careerProspectsEn || item?.career_prospects_en),
      applicationStepsAr: parseTextList(item?.applicationStepsAr || item?.application_steps_ar),
      applicationStepsEn: parseTextList(item?.applicationStepsEn || item?.application_steps_en),
      whyProgramAr: parseTextList(item?.whyProgramAr || item?.why_program_ar),
      whyProgramEn: parseTextList(item?.whyProgramEn || item?.why_program_en),
      facultyMembers: Array.isArray(item?.facultyMembers) ? item.facultyMembers : [],
    }))
  } catch {
    return []
  }
}

function normalizeProgram(item: any): AcademicProgram {
  const objectivesRaw = Array.isArray(item?.objectives) ? item.objectives : []
  return {
    id: safeString(item?.id || item?.docname),
    nameAr: safeString(item?.nameAr || item?.name_ar || item?.programName || item?.program_name),
    nameEn: safeString(item?.nameEn || item?.name_en || item?.programName || item?.program_name),
    departmentAr: safeString(item?.departmentAr || item?.department_ar),
    departmentEn: safeString(item?.departmentEn || item?.department_en),
    degreeType: safeString(item?.degreeType || item?.degree_type),
    admissionRate: safeNumber(item?.admissionRate || item?.admission_rate),
    highSchoolType: safeString(item?.highSchoolType || item?.high_school_type || 'علمي') as AcademicProgram['highSchoolType'],
    highSchoolTypeEn: safeString(item?.highSchoolTypeEn || item?.high_school_type_en || 'Scientific') as AcademicProgram['highSchoolTypeEn'],
    studyYears: safeString(item?.studyYears || item?.study_years || item?.duration),
    image: safeString(item?.image),
    descriptionAr: safeString(item?.descriptionAr || item?.description_ar || item?.description),
    descriptionEn: safeString(item?.descriptionEn || item?.description_en || item?.description),
    objectives: objectivesRaw.map((objective: any, index: number) => ({
      id: safeString(objective?.id || `objective-${index + 1}`),
      textAr: safeString(objective?.textAr || objective?.text_ar),
      textEn: safeString(objective?.textEn || objective?.text_en),
    })),
    careerProspectsAr: parseTextList(item?.careerProspectsAr || item?.career_prospects_ar),
    careerProspectsEn: parseTextList(item?.careerProspectsEn || item?.career_prospects_en),
    applicationStepsAr: parseTextList(item?.applicationStepsAr || item?.application_steps_ar),
    applicationStepsEn: parseTextList(item?.applicationStepsEn || item?.application_steps_en),
    whyProgramAr: parseTextList(item?.whyProgramAr || item?.why_program_ar),
    whyProgramEn: parseTextList(item?.whyProgramEn || item?.why_program_en),
    facultyMembers: Array.isArray(item?.facultyMembers) ? item.facultyMembers : [],
  }
}

function normalizeCollege(item: any, programs: AcademicProgram[]): College {
  return {
    id: safeString(item?.id || item?.docname),
    slug: safeString(item?.slug || item?.nameEn || item?.nameAr || item?.collegeName).toLowerCase().replace(/\s+/g, '-'),
    nameAr: safeString(item?.nameAr || item?.collegeName),
    nameEn: safeString(item?.nameEn || item?.collegeName),
    deanNameAr: safeString(item?.deanName || item?.dean_name_ar || item?.dean_name),
    deanNameEn: safeString(item?.deanNameEn || item?.dean_name_en),
    deanImage: safeString(item?.deanImage || item?.dean_image),
    descriptionAr: safeString(item?.descriptionAr || item?.description || item?.description_ar),
    descriptionEn: safeString(item?.descriptionEn || item?.description_en),
    visionAr: safeString(item?.visionAr),
    visionEn: safeString(item?.visionEn),
    missionAr: safeString(item?.missionAr),
    missionEn: safeString(item?.missionEn),
    goalsAr: safeString(item?.goalsAr),
    goalsEn: safeString(item?.goalsEn),
    valuesAr: safeString(item?.valuesAr),
    valuesEn: safeString(item?.valuesEn),
    qualityAr: safeString(item?.qualityAr),
    qualityEn: safeString(item?.qualityEn),
    strategyAr: safeString(item?.strategyAr),
    strategyEn: safeString(item?.strategyEn),
    icon: item?.icon || '',
    image: item?.image || '',
    backgroundImage: item?.backgroundImage || item?.background_image || item?.image || '',
    news: [],
    programs,
  }
}

export async function getAdminColleges() {
  const [collegesRaw, programsRaw] = await Promise.all([
    portalRequest<any[]>('/api/colleges'),
    portalRequest<any[]>('/api/programs'),
  ])

  const normalizedPrograms = programsRaw.map(normalizeProgram)
  const groupedPrograms = new Map<string, AcademicProgram[]>()
  normalizedPrograms.forEach((program, index) => {
    const collegeKey = safeString(programsRaw[index]?.college)
    if (!collegeKey) return
    const current = groupedPrograms.get(collegeKey) || []
    current.push(program)
    groupedPrograms.set(collegeKey, current)
  })

  return collegesRaw.map((item) => {
    const docname = safeString(item?.docname || item?.id)
    const directPrograms = parseProgramsJson(item?.programsJson)
    const linkedPrograms = groupedPrograms.get(docname) || []
    const programs = linkedPrograms.length > 0 ? linkedPrograms : directPrograms
    return normalizeCollege(item, programs)
  })
}

export async function createCollege(data: CollegePayload) {
  return portalRequest<any>('/api/colleges', {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

export async function updateCollege(id: string, data: Partial<CollegePayload>) {
  return portalRequest<any>(`/api/colleges/${encodeURIComponent(id)}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  })
}

export async function deleteCollege(id: string) {
  return portalRequest<{ deleted: boolean }>(`/api/colleges/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  })
}

export async function createProgram(data: ProgramPayload) {
  return portalRequest<any>('/api/programs', {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

export async function updateProgram(id: string, data: Partial<ProgramPayload>) {
  return portalRequest<any>(`/api/programs/${encodeURIComponent(id)}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  })
}

export async function deleteProgram(id: string) {
  return portalRequest<{ deleted: boolean }>(`/api/programs/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  })
}
