"use client"
import React from 'react'
import Collapse from './Collapse'
import ScheduleCollapse from './ScheduleCollapse'
import { CoursesProps, ScheduleProps, RerganizedScheduleProps } from '@/types'


async function reorganizedSchedule(schedule: ScheduleProps[]) {

    const sortedSchedule = schedule.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

    // Then, reorganize the sorted schedule
    const reorganizedSchedule = sortedSchedule.reduce<Record<string, { yearAndMonth: string; schedule: ScheduleProps[] }>>((acc, item) => {
        const date = new Date(item.date);
        const yearMonth = `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月`;

        if (!acc[yearMonth]) {
            acc[yearMonth] = {
                yearAndMonth: yearMonth,
                schedule: []
            };
        }

        acc[yearMonth].schedule.push(item);

        return acc;
    }, {});

    return Object.values(reorganizedSchedule);
}



const Accordion = async ({ courseData }: { courseData: CoursesProps }) => {
    const newSchedule = await reorganizedSchedule(courseData.schedule)

    return (
        <div className='relative flex flex-col w-full h-auto items-center pb-60'>
            <Collapse title='課程資訊' children={courseData.information} />
            <Collapse title='課程內容' children={courseData.contant} info={true} info_images={courseData.info_images} />
            <Collapse title='備註' children={courseData.remark} />
            <p className='text-5xl text-center mt-48'>
                {"課程時間表"}
            </p>
            {
                newSchedule.map((item, index) => {
                    return (
                        <ScheduleCollapse key={index} title={item.yearAndMonth} rerganizedSchedule={{ yearAndMonth: item.yearAndMonth, schedules: item.schedule }} />
                    )
                })
            }
            <div className="bg-[url('/images/014.png')] absolute bottom-0 inset-0 h-auto w-full bg-contain bg-bottom bg-no-repeat -z-10"></div>

        </div>
    )
}

export default Accordion
