import { College, FacultyMember } 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 COLLEGES_LIST_ENDPOINT = '/api/aau/colleges'
const COLLEGES_DETAIL_ENDPOINT = '/api/aau/colleges'
const PROGRAMS_LIST_ENDPOINT = '/api/programs?limit=500'
const COLLEGE_PROGRAMS_ENDPOINT = '/api/colleges'

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

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

    return response.json()
}

function unwrapCollegePayload(payload: any) {
    if (payload?.ok && payload?.data) {
        return payload.data
    }

    if (payload?.message?.ok && payload?.message?.data) {
        return payload.message.data
    }

    if (payload?.data?.ok && payload?.data?.data) {
        return payload.data.data
    }

    if (payload?.data) {
        return payload.data
    }

    return payload
}

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

function mapProgram(program: any) {
    const objectives = Array.isArray(program?.objectives) ? program.objectives : []
    const facultyMembers = Array.isArray(program?.facultyMembers) ? program.facultyMembers : []
    const careerProspectsAr = Array.isArray(program?.careerProspectsAr) ? program.careerProspectsAr : []
    const careerProspectsEn = Array.isArray(program?.careerProspectsEn) ? program.careerProspectsEn : []
    const applicationStepsAr = Array.isArray(program?.applicationStepsAr) ? program.applicationStepsAr : []
    const applicationStepsEn = Array.isArray(program?.applicationStepsEn) ? program.applicationStepsEn : []
    const whyProgramAr = Array.isArray(program?.whyProgramAr) ? program.whyProgramAr : []
    const whyProgramEn = Array.isArray(program?.whyProgramEn) ? program.whyProgramEn : []

    return {
        id: String(program?.id || program?.name || program?.programName || ''),
        nameAr: String(program?.nameAr || program?.programName || ''),
        nameEn: String(program?.nameEn || ''),
        departmentAr: String(program?.departmentAr || ''),
        departmentEn: String(program?.departmentEn || ''),
        degreeType: String(program?.degreeType || ''),
        admissionRate: Number(program?.admissionRate || 0),
        highSchoolType: program?.highSchoolType || 'علمي',
        highSchoolTypeEn: program?.highSchoolTypeEn || '',
        studyYears: String(program?.studyYears || program?.duration || ''),
        studyYearsEn: String(program?.studyYearsEn || program?.durationEn || program?.studyYears || program?.duration || ''),
        image: resolveMediaUrl(program?.image),
        updatedAt: String(program?.updatedAt || program?.modified || ''),
        descriptionAr: String(program?.descriptionAr || program?.description || ''),
        descriptionEn: String(program?.descriptionEn || ''),
        objectives: objectives.map((item: any, index: number) => ({
            id: String(item?.id || `objective-${index + 1}`),
            textAr: String(item?.textAr || ''),
            textEn: String(item?.textEn || ''),
        })),
        studyPlan: [],
        careerProspectsAr: careerProspectsAr.map((item: any) => String(item || '')).filter(Boolean),
        careerProspectsEn: careerProspectsEn.map((item: any) => String(item || '')).filter(Boolean),
        applicationStepsAr: applicationStepsAr.map((item: any) => String(item || '')).filter(Boolean),
        applicationStepsEn: applicationStepsEn.map((item: any) => String(item || '')).filter(Boolean),
        whyProgramAr: whyProgramAr.map((item: any) => String(item || '')).filter(Boolean),
        whyProgramEn: whyProgramEn.map((item: any) => String(item || '')).filter(Boolean),
        facultyMembers: facultyMembers.map((item: any) => ({
            id: String(item?.id || ''),
            nameAr: String(item?.nameAr || ''),
            nameEn: String(item?.nameEn || ''),
            titleAr: String(item?.titleAr || ''),
            titleEn: String(item?.titleEn || ''),
            image: resolveMediaUrl(item?.image),
            email: String(item?.email || ''),
            specializationAr: String(item?.specializationAr || ''),
            specializationEn: String(item?.specializationEn || ''),
        })),
    }
}

function mapFacultyMember(item: any): FacultyMember {
    return {
        id: String(item?.id || ''),
        nameAr: String(item?.nameAr || ''),
        nameEn: String(item?.nameEn || ''),
        degreeAr: String(item?.degreeAr || ''),
        degreeEn: String(item?.degreeEn || ''),
        specializationAr: String(item?.specializationAr || item?.departmentAr || ''),
        specializationEn: String(item?.specializationEn || item?.departmentEn || ''),
        collegeAr: String(item?.collegeAr || ''),
        collegeEn: String(item?.collegeEn || ''),
        departmentAr: String(item?.departmentAr || ''),
        departmentEn: String(item?.departmentEn || ''),
        email: String(item?.email || ''),
        phone: String(item?.phone || ''),
        bioAr: String(item?.bioAr || ''),
        bioEn: String(item?.bioEn || ''),
        image: resolveMediaUrl(item?.image),
    }
}

function mapCollege(item: any): College {
    const fallbackName = String(item?.collegeName || item?.nameAr || item?.nameEn || item?.title || '').trim()
    const slug = normalizeCollegeId(item?.slug || item?.id || item?.name || fallbackName)
    const backendId = normalizeCollegeId(item?.id || item?.docname || item?.name || slug)

    return {
        id: slug,
        slug,
        backendId,
        updatedAt: String(item?.updatedAt || item?.modified || ''),
        collegeName: fallbackName,
        nameAr: String(item?.nameAr || item?.collegeName || ''),
        nameEn: String(item?.nameEn || ''),
        deanNameAr: String(item?.deanName || item?.deanNameAr || item?.dean_name_ar || item?.dean_name || ''),
        deanNameEn: String(item?.deanNameEn || item?.dean_name_en || ''),
        deanImage: resolveMediaUrl(item?.deanImage || item?.dean_image),
        departmentHeadNameAr: String(item?.departmentHeadName || item?.departmentHeadNameAr || item?.department_head_name || ''),
        departmentHeadNameEn: String(item?.departmentHeadNameEn || item?.department_head_name_en || ''),
        departmentHeadImage: resolveMediaUrl(item?.departmentHeadImage || item?.department_head_image),
        descriptionAr: String(item?.descriptionAr || ''),
        descriptionEn: String(item?.descriptionEn || ''),
        visionAr: String(item?.visionAr || ''),
        visionEn: String(item?.visionEn || ''),
        missionAr: String(item?.missionAr || ''),
        missionEn: String(item?.missionEn || ''),
        goalsAr: String(item?.goalsAr || ''),
        goalsEn: String(item?.goalsEn || ''),
        valuesAr: String(item?.valuesAr || ''),
        valuesEn: String(item?.valuesEn || ''),
        qualityAr: String(item?.qualityAr || ''),
        qualityEn: String(item?.qualityEn || ''),
        strategyAr: String(item?.strategyAr || ''),
        strategyEn: String(item?.strategyEn || ''),
        icon: item?.icon || '',
        image: resolveMediaUrl(item?.image),
        backgroundImage: resolveMediaUrl(item?.backgroundImage || item?.background_image || item?.image),
        programs: Array.isArray(item?.programs) ? item.programs.map(mapProgram) : [],
        programsCount: Number(item?.programsCount ?? item?.programs_count ?? (Array.isArray(item?.programs) ? item.programs.length : 0)),
        departmentsCount: Number(item?.departmentsCount ?? item?.departments_count ?? 0),
        facultyCount: Number(item?.facultyCount ?? item?.faculty_count ?? 0),
        news: Array.isArray(item?.news)
            ? item.news.map((news: any) => ({
                id: String(news?.id || news?.slug || ''),
                slug: String(news?.slug || news?.id || ''),
                titleAr: String(news?.titleAr || ''),
                titleEn: String(news?.titleEn || ''),
                descAr: String(news?.descAr || ''),
                descEn: String(news?.descEn || ''),
                date: String(news?.date || ''),
                image: resolveMediaUrl(news?.image) || '',
                collegeId: slug,
            }))
            : [],
    }
}

export async function getCollegesList(): Promise<College[]> {
    try {
        const payload = await fetchCollegesJson(COLLEGES_LIST_ENDPOINT)
        const data = unwrapCollegePayload(payload)
        const items = Array.isArray(data?.items) ? data.items : Array.isArray(payload?.items) ? payload.items : []

        return items
            .map(mapCollege)
            .filter((college) => Boolean(college.id && (college.nameAr || college.nameEn || college.collegeName)))
    } catch {
        return []
    }
}

export async function getCollegeById(id: string): Promise<College | null> {
    try {
        const payload = await fetchCollegesJson(`${COLLEGES_DETAIL_ENDPOINT}/${encodeURIComponent(id)}`)
        const data = unwrapCollegePayload(payload)
        const college = mapCollege(data)
        const programsPayload = await fetchCollegesJson(`${COLLEGE_PROGRAMS_ENDPOINT}/${encodeURIComponent(college.backendId || college.id)}/programs`)
        const programsData = unwrapCollegePayload(programsPayload)
        const programs = Array.isArray(programsData) ? programsData : Array.isArray(programsData?.items) ? programsData.items : []
        return {
            ...college,
            programs: programs.map(mapProgram),
        }
    } catch {
        try {
            const colleges = await getCollegesList()
            const college = colleges.find((item) => item.id === id || item.slug === id || item.backendId === id) || null
            if (!college) {
                return null
            }
            const programsPayload = await fetchCollegesJson(`${COLLEGE_PROGRAMS_ENDPOINT}/${encodeURIComponent(college.backendId || college.id)}/programs`)
            const programsData = unwrapCollegePayload(programsPayload)
            const programs = Array.isArray(programsData) ? programsData : Array.isArray(programsData?.items) ? programsData.items : []
            return {
                ...college,
                programs: programs.map(mapProgram),
            }
        } catch {
            return null
        }
    }
}

export async function getCollegeFaculty(_college: College): Promise<FacultyMember[]> {
    try {
        const payload = await fetchCollegesJson(`${COLLEGE_PROGRAMS_ENDPOINT}/${encodeURIComponent(_college.backendId || _college.id)}/faculty`)
        const data = unwrapCollegePayload(payload)
        const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : []
        return items.map(mapFacultyMember)
    } catch {
        return []
    }
}

export async function getProgramByIds(collegeId: string, programId: string) {
    const college = await getCollegeById(collegeId)
    if (!college) {
        return null
    }

    const program = college.programs.find((entry) => entry.id === programId) || null
    if (!program) {
        return null
    }

    return { college, program }
}

export async function getProgramsForCollege(collegeId: string) {
    try {
        const payload = await fetchCollegesJson(`${COLLEGE_PROGRAMS_ENDPOINT}/${encodeURIComponent(collegeId)}/programs`)
        const data = unwrapCollegePayload(payload)
        const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : []
        return items.map(mapProgram)
    } catch {
        return []
    }
}

export async function getAcademicProgramsCount(): Promise<number> {
    try {
        const payload = await fetchCollegesJson(PROGRAMS_LIST_ENDPOINT)
        const data = unwrapCollegePayload(payload)
        const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : []

        return items.filter((program) => {
            const isActive = Number(program?.isActive ?? program?.is_active ?? 0) === 1
            const college = String(program?.college || '').trim()
            return isActive && Boolean(college)
        }).length
    } catch {
        return 0
    }
}
