'use client';

import { useMemo, useState, useEffect } from "react";
import CourseCard from "./CourseCard";
import apiService from "@/app/lib/apiService";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";

type CourseStatus = "전체" | "수강 예정" | "수강중" | "수강 완료";

type Lesson = {
	id: string;
	title: string;
	durationMin: number;
	progressPct: number;
	isCompleted: boolean;
};

type Course = {
	id: string;
	title: string;
	description: string;
	thumbnail: string;
	status: CourseStatus;
	progressPct: number;
	lessons: Lesson[];
};

const TABS: CourseStatus[] = ["전체", "수강중", "수강 완료"];
const ITEMS_PER_PAGE = 5;

export default function CoursesPage() {
	const [activeTab, setActiveTab] = useState<CourseStatus>("전체");
	const [courses, setCourses] = useState<Course[]>([]);
	const [loading, setLoading] = useState(true);
	const [currentPage, setCurrentPage] = useState(1);

	useEffect(() => {
		const fetchCourses = async () => {
			try {
				setLoading(true);

				// 1. getSubjects()로 모든 subject 조회
				let allSubjects: any[] = [];
				try {
					const subjectsResponse = await apiService.getSubjects();
					if (Array.isArray(subjectsResponse.data)) {
						allSubjects = subjectsResponse.data;
					} else if (subjectsResponse.data && typeof subjectsResponse.data === 'object') {
						allSubjects = subjectsResponse.data.items ||
							subjectsResponse.data.subjects ||
							subjectsResponse.data.data ||
							subjectsResponse.data.list ||
							subjectsResponse.data.subjectList ||
							[];
					}
				} catch (subjectsErr) {
					console.error('getSubjects 실패:', subjectsErr);
				}

				// subject 정보를 Map으로 변환 (subjectId로 빠르게 조회)
				const subjectMap: Record<string, any> = {};
				allSubjects.forEach((subject: any) => {
					const subjectId = String(subject.id || subject.subjectId || '');
					if (subjectId) {
						subjectMap[subjectId] = subject;
					}
				});

				// 2. getLectures()로 모든 lecture 조회
				let allLectures: any[] = [];
				try {
					const lecturesResponse = await apiService.getLectures();
					if (Array.isArray(lecturesResponse.data)) {
						allLectures = lecturesResponse.data;
					} else if (lecturesResponse.data && typeof lecturesResponse.data === 'object') {
						allLectures = lecturesResponse.data.items ||
							lecturesResponse.data.lectures ||
							lecturesResponse.data.data ||
							lecturesResponse.data.list ||
							[];
					}
				} catch (lecturesErr) {
					console.error('getLectures 실패:', lecturesErr);
					setCourses([]);
					setLoading(false);
					return;
				}

				// 3. 각 lecture의 ID 추출
				const lectureIds = allLectures.map((lecture: any) =>
					String(lecture.id || lecture.lectureId || '')
				).filter((id: string) => id);

				// 4. 각 lectureId에 대해 진행률 조회
				const progressMap: Record<string, any> = {};
				await Promise.all(
					lectureIds.map(async (lectureId) => {
						try {
							const progressResponse = await apiService.getLectureProgress(lectureId);
							if (progressResponse?.data) {
								progressMap[lectureId] = progressResponse.data;
							}
						} catch (progressErr) {
							// 진행률이 없으면 무시
							console.log(`Lecture ${lectureId} 진행률 조회 실패:`, progressErr);
						}
					})
				);

				// 5. 진행률이 있는 lecture만 필터링
				const lecturesWithProgress = allLectures.filter((lecture: any) => {
					const lectureId = String(lecture.id || lecture.lectureId || '');
					return progressMap[lectureId];
				});

				// 6. 교육과정(subjectId)별로 그룹화
				const coursesBySubject: Record<string, {
					subjectId: string;
					subjectName: string;
					subjectDescription: string;
					subjectImageKey?: string;
					lectures: any[];
				}> = {};

				lecturesWithProgress.forEach((lecture: any) => {
					const subjectId = String(lecture.subjectId || lecture.subject_id || '');
					const lectureId = String(lecture.id || lecture.lectureId || '');

					if (!subjectId || !lectureId) return;

					// subject 정보 가져오기
					const subject = subjectMap[subjectId];

					if (!coursesBySubject[subjectId]) {
						coursesBySubject[subjectId] = {
							subjectId,
							subjectName: subject?.title || subject?.name || subject?.subjectName || lecture.subjectName || lecture.subject_name || lecture.subject?.name || '',
							subjectDescription: subject?.description || subject?.subjectDescription || lecture.subjectDescription || lecture.subject_description || lecture.subject?.description || '',
							subjectImageKey: subject?.imageKey || subject?.image_key || subject?.fileKey || lecture.subjectImageKey || lecture.subject_image_key || lecture.subject?.imageKey,
							lectures: [],
						};
					}

					coursesBySubject[subjectId].lectures.push({
						...lecture,
						progress: progressMap[lectureId],
					});
				});

				// 6. Course 타입으로 변환
				const transformedCourses: Course[] = await Promise.all(
					Object.values(coursesBySubject).map(async (courseData) => {
						// 썸네일 이미지 가져오기
						let thumbnail = '/imgs/talk.png';
						if (courseData.subjectImageKey) {
							try {
								const imageUrl = await apiService.getFile(courseData.subjectImageKey);
								if (imageUrl) {
									thumbnail = imageUrl;
								}
							} catch (imgErr) {
								console.error('이미지 다운로드 실패:', imgErr);
							}
						}

						// lessons 변환 (lecture를 lesson으로 변환)
						const transformedLessons: Lesson[] = courseData.lectures.map((lecture: any, index: number) => {
							const lectureId = String(lecture.id || lecture.lectureId || '');
							const progress = lecture.progress || progressMap[lectureId];
							const progressPct = progress?.progressPct ||
								progress?.progress_pct ||
								progress?.progressRate ||
								progress?.progress_rate ||
								0;
							// isCompleted는 progress 데이터에서 가져오거나, progressPct가 100이면 완료
							const isCompleted = progress?.isCompleted ||
								progress?.is_completed ||
								progressPct === 100 ||
								false;

							return {
								id: lectureId,
								title: lecture.title || lecture.lectureName || lecture.lecture_name || lecture.name || `강의 ${index + 1}`,
								durationMin: lecture.durationMin || lecture.duration_min || lecture.duration || 0,
								progressPct: progressPct,
								isCompleted,
							};
						});

						// 전체 진행률 계산 (모든 lecture의 진행률 평균)
						let totalLectureProgress = 0;
						let totalLectures = 0;
						let allCompleted = true;
						let hasProgress = false;

						courseData.lectures.forEach((lecture: any) => {
							const lectureId = String(lecture.id || lecture.lectureId || '');
							const progress = lecture.progress || progressMap[lectureId];

							// progress 데이터가 있으면 무조건 수강중 또는 수강 완료
							if (progress) {
								hasProgress = true;
							}

							const progressPct = progress?.progressPct ||
								progress?.progress_pct ||
								progress?.progressRate ||
								progress?.progress_rate ||
								0;
							const isCompleted = progress?.isCompleted ||
								progress?.is_completed ||
								progressPct === 100 ||
								false;

							totalLectureProgress += progressPct;
							totalLectures += 1;

							if (!isCompleted) {
								allCompleted = false;
							}
						});

						const avgProgress = totalLectures > 0 ? Math.round(totalLectureProgress / totalLectures) : 0;

						// 상태 결정: 수강 완료 = isCompleted가 true, 수강중 = isCompleted가 false이고 progress 데이터가 있는 경우
						// progress 데이터가 있으면 무조건 "수강중" 또는 "수강 완료"
						let status: CourseStatus = "수강 예정";
						if (allCompleted) {
							status = "수강 완료";
						} else if (hasProgress) {
							status = "수강중";
						}

						return {
							id: courseData.subjectId,
							title: courseData.subjectName || '제목 없음',
							description: courseData.subjectDescription || '',
							thumbnail,
							status,
							progressPct: avgProgress,
							lessons: transformedLessons,
						};
					})
				);

				// "수강 예정" 상태 제거 (수강중, 수강 완료만 표시)
				const filteredCourses = transformedCourses.filter((course) =>
					course.status === "수강중" || course.status === "수강 완료"
				);

				// 디버깅: 데이터 확인
				console.log('🔍 [CoursesPage] 전체 courses:', transformedCourses);
				console.log('🔍 [CoursesPage] 필터링된 courses:', filteredCourses);
				console.log('🔍 [CoursesPage] progressMap:', progressMap);

				setCourses(filteredCourses);
			} catch (err) {
				console.error('강좌 조회 실패:', err);
				setCourses([]);
			} finally {
				setLoading(false);
			}
		};

		fetchCourses();
	}, []);

	const countsByStatus = useMemo(() => {
		return {
			전체: courses.length,
			수강중: courses.filter((c) => c.status === "수강중").length,
			"수강 완료": courses.filter((c) => c.status === "수강 완료").length,
		};
	}, [courses]);

	const filtered = useMemo(() => {
		if (activeTab === "전체") return courses;
		return courses.filter((c) => c.status === activeTab);
	}, [activeTab, courses]);

	// 탭 변경 시 첫 페이지로 리셋
	useEffect(() => {
		setCurrentPage(1);
	}, [activeTab]);

	const totalCount = useMemo(() => filtered.length, [filtered]);
	const totalPages = Math.ceil(totalCount / ITEMS_PER_PAGE);
	const pagedCourses = useMemo(
		() => filtered.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE),
		[filtered, currentPage]
	);

	// 페이지네이션: 10개씩 표시
	const pageGroup = Math.floor((currentPage - 1) / 10);
	const startPage = pageGroup * 10 + 1;
	const endPage = Math.min(startPage + 9, totalPages);
	const visiblePages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);

	return (
		<main className="flex w-full flex-col">
			<div className="flex h-[100px] items-center px-8">
				<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">내 강좌실</h1>
			</div>

			<div className="px-8">
				<div className="border-b border-[#ecf0ff]">
					<ul className="flex gap-6">
						{TABS.map((tab) => {
							const isActive = activeTab === tab;
							return (
								<li key={tab}>
									<button
										type="button"
										onClick={() => setActiveTab(tab)}
										className={[
											"relative -mb-px h-12 px-1 text-[14px] leading-[1.5]",
											isActive ? "font-semibold text-[#1f2b91]" : "font-medium text-[#6c7682]",
										].join(" ")}
									>
										{tab}{" "}
										<span className="ml-1 text-[#8c95a1]">
											{countsByStatus[tab as keyof typeof countsByStatus] ?? 0}
										</span>
										{isActive ? (
											<span className="absolute inset-x-0 -bottom-[1px] h-[2px] bg-[#1f2b91]" />
										) : null}
									</button>
								</li>
							);
						})}
					</ul>
				</div>
			</div>

			<div className="px-8 pb-16 pt-6">
				{loading ? (
					<div className="flex items-center justify-center py-16">
						<p className="text-[14px] text-text-meta">로딩 중...</p>
					</div>
				) : filtered.length === 0 ? (
					<div className="flex items-center justify-center py-16">
						<p className="text-[14px] text-text-meta">수강 중인 강좌가 없습니다.</p>
					</div>
				) : (
					<div className="flex flex-col gap-4">
						{pagedCourses.map((course) => (
							<CourseCard key={course.id} course={course} />
						))}
					</div>
				)}

				{/* 페이지네이션 - 5개 초과일 때만 표시 */}
				{totalCount > ITEMS_PER_PAGE && (
					<div className="mt-10 flex items-center justify-center">
						<div className="flex items-center justify-center gap-[8px]">
							{/* First (맨 앞으로) */}
							<button
								type="button"
								onClick={() => setCurrentPage(1)}
								aria-label="맨 앞 페이지"
								className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-neutral-700 disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
								disabled={currentPage === 1}
							>
								<div className="relative flex items-center justify-center w-full h-full">
									<ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute left-[2px]" />
									<ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute right-[2px]" />
								</div>
							</button>

							{/* Prev */}
							<button
								type="button"
								onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
								aria-label="이전 페이지"
								className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-neutral-700 disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
								disabled={currentPage === 1}
							>
								<ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
							</button>

							{/* Numbers */}
							{visiblePages.map((n) => {
								const active = n === currentPage;
								return (
									<button
										key={n}
										type="button"
										onClick={() => setCurrentPage(n)}
										aria-current={active ? 'page' : undefined}
										className={[
											'flex items-center justify-center rounded-[1000px] size-[32px] cursor-pointer',
											active ? 'bg-bg-primary-light' : 'bg-white',
										].join(' ')}
									>
										<span className="text-[16px] leading-[1.4] text-neutral-700">{n}</span>
									</button>
								);
							})}

							{/* Next */}
							<button
								type="button"
								onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
								aria-label="다음 페이지"
								className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-neutral-700 disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
								disabled={currentPage === totalPages}
							>
								<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90" />
							</button>

							{/* Last (맨 뒤로) */}
							<button
								type="button"
								onClick={() => setCurrentPage(totalPages)}
								aria-label="맨 뒤 페이지"
								className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-neutral-700 disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
								disabled={currentPage === totalPages}
							>
								<div className="relative flex items-center justify-center w-full h-full">
									<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute left-[2px]" />
									<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute right-[2px]" />
								</div>
							</button>
						</div>
					</div>
				)}
			</div>
		</main>
	);
}

