'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import apiService from '../../lib/apiService';
import BackCircleSvg from '../../svgs/backcirclesvg';

const imgPlay = '/imgs/play.svg';
const imgMusicAudioPlay = '/imgs/music-audio-play.svg';

type Lesson = {
	id: string;
	title: string;
	duration: string; // "12:46" 형식
	state: "제출완료" | "제출대기";
	action: "복습하기" | "이어서 수강하기" | "수강하기";
};

type CourseDetail = {
	id: string;
	status: "수강 중" | "수강 예정" | "수강 완료";
	title: string;
	goal: string;
	method: string;
	summary: string; // VOD · 총 n강 · n시간 n분
	submitSummary: string; // 학습 제출 n/n
	thumbnail: string;
	lessons: Lesson[];
};

export default function CourseDetailPage() {
	const params = useParams();
	const router = useRouter();
	const [course, setCourse] = useState<CourseDetail | null>(null);
	const [lectures, setLectures] = useState<any[]>([]);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string | null>(null);
	const [lectureProgresses, setLectureProgresses] = useState<Record<string, any>>({});

	useEffect(() => {
		const fetchCourse = async () => {
			if (!params?.id) return;

			try {
				setLoading(true);
				setError(null);

				let data: any = null;
				const subjectId = String(params.id);

				// getSubjects로 과목 정보 가져오기
				try {
					const subjectsResponse = await apiService.getSubjects();
					let subjectsData: any[] = [];

					if (Array.isArray(subjectsResponse.data)) {
						subjectsData = subjectsResponse.data;
					} else if (subjectsResponse.data && typeof subjectsResponse.data === 'object') {
						subjectsData = subjectsResponse.data.items ||
							subjectsResponse.data.courses ||
							subjectsResponse.data.data ||
							subjectsResponse.data.list ||
							subjectsResponse.data.subjects ||
							subjectsResponse.data.subjectList ||
							[];
					}

					// ID로 과목 찾기
					data = subjectsData.find((s: any) => String(s.id || s.subjectId) === subjectId);
				} catch (subjectsErr) {
					console.error('getSubjects 실패:', subjectsErr);
				}

				if (!data) {
					throw new Error('강좌를 찾을 수 없습니다.');
				}

				// 썸네일 이미지 가져오기
				let thumbnail = '/imgs/talk.png';
				if (data.imageKey) {
					try {
						const imageUrl = await apiService.getFile(data.imageKey);
						if (imageUrl) {
							thumbnail = imageUrl;
						}
					} catch (imgErr) {
						console.error('이미지 다운로드 실패:', imgErr);
					}
				}

				// 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 ||
							[];
					}

					// subjectId로 필터링
					const filteredLectures = allLectures.filter((lecture: any) =>
						String(lecture.subjectId || lecture.subject_id) === subjectId
					);

					setLectures(filteredLectures);

					// 각 lecture의 진행률 조회
					const progressMap: Record<string, any> = {};
					await Promise.all(
						filteredLectures.map(async (lecture: any) => {
							const lectureId = lecture.id || lecture.lectureId;
							if (lectureId) {
								try {
									const progressResponse = await apiService.getLectureProgress(lectureId);
									if (progressResponse?.data) {
										progressMap[String(lectureId)] = progressResponse.data;
									}
								} catch (progressErr) {
									// 진행률이 없으면 무시 (에러가 아닐 수 있음)
									console.log(`Lecture ${lectureId} 진행률 조회 실패:`, progressErr);
								}
							}
						})
					);
					setLectureProgresses(progressMap);

					// API 응답 데이터를 CourseDetail 타입으로 변환
					const courseDetail: CourseDetail = {
						id: String(data.id || params.id),
						status: data.status || "수강 예정",
						title: data.title || data.lectureName || data.subjectName || '',
						goal: data.objective || data.goal || '',
						method: data.method || '',
						summary: data.summary || `VOD · 총 ${filteredLectures.length || 0}강`,
						submitSummary: data.submitSummary || '',
						thumbnail: thumbnail,
						lessons: [],
					};

					setCourse(courseDetail);
				} catch (lecturesErr) {
					console.error('getLectures 실패:', lecturesErr);

					// API 응답 데이터를 CourseDetail 타입으로 변환 (lecture 없이)
					const courseDetail: CourseDetail = {
						id: String(data.id || params.id),
						status: data.status || "수강 예정",
						title: data.title || data.lectureName || data.subjectName || '',
						goal: data.objective || data.goal || '',
						method: data.method || '',
						summary: data.summary || `VOD · 총 0강`,
						submitSummary: data.submitSummary || '',
						thumbnail: thumbnail,
						lessons: [],
					};

					setCourse(courseDetail);
				}
			} catch (err) {
				console.error('강좌 조회 실패:', err);
				setError(err instanceof Error ? err.message : '강좌를 불러오는데 실패했습니다.');
			} finally {
				setLoading(false);
			}
		};

		fetchCourse();
	}, [params?.id]);

	if (loading) {
		return (
			<main className="flex w-full flex-col items-center">
				<div className="flex h-[100px] w-full max-w-[1440px] items-center gap-[12px] px-8">
					<button
						type="button"
						onClick={() => router.back()}
						aria-label="뒤로 가기"
						className="size-8 rounded-full inline-flex items-center justify-center text-[#8C95A1] hover:bg-black/5 no-underline cursor-pointer"
					>
						<BackCircleSvg width={32} height={32} />
					</button>
					<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">교육 과정 상세보기</h1>
				</div>
				<section className="w-full max-w-[1440px] px-8 pb-20">
					<div className="flex items-center justify-center py-20">
						<p className="text-[16px] text-[#8c95a1]">로딩 중...</p>
					</div>
				</section>
			</main>
		);
	}

	if (error || !course) {
		return (
			<main className="flex w-full flex-col items-center">
				<div className="flex h-[100px] w-full max-w-[1440px] items-center gap-[12px] px-8">
					<button
						type="button"
						onClick={() => router.back()}
						aria-label="뒤로 가기"
						className="size-8 rounded-full inline-flex items-center justify-center text-[#8C95A1] hover:bg-black/5 no-underline cursor-pointer"
					>
						<BackCircleSvg width={32} height={32} />
					</button>
					<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">교육 과정 상세보기</h1>
				</div>
				<section className="w-full max-w-[1440px] px-8 pb-20">
					<div className="flex flex-col items-center justify-center py-20">
						<p className="text-[16px] text-red-500 mb-4">{error || '강좌를 찾을 수 없습니다.'}</p>
						<button
							type="button"
							onClick={() => router.push('/course-list')}
							className="px-4 py-2 rounded-[6px] bg-primary text-white text-[14px] font-medium"
						>
							강좌 목록으로 돌아가기
						</button>
					</div>
				</section>
			</main>
		);
	}

	return (
		<main className="flex w-full flex-col items-center">
			{/* 헤더 */}
			<div className="flex h-[100px] w-full max-w-[1440px] items-center gap-[12px] px-8">
				<button
					type="button"
					onClick={() => router.back()}
					aria-label="뒤로 가기"
					className="size-8 rounded-full inline-flex items-center justify-center text-[#8C95A1] hover:bg-black/5 no-underline cursor-pointer"
				>
					<BackCircleSvg width={32} height={32} />
				</button>
				<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">교육 과정 상세보기</h1>
			</div>

			{/* 메인 콘텐츠 */}
			<section className="w-full max-w-[1440px] px-8 pb-[80px] pt-[24px]">
				{/* 상단 정보 카드 */}
				<div className="bg-[#f8f9fa] box-border flex gap-[24px] items-start p-[24px] rounded-[8px] w-full">
					{/* 이미지 컨테이너 */}
					<div className="overflow-clip relative rounded-[4px] shrink-0 w-[220.5px] h-[159px]">
						<Image
							src={course.thumbnail}
							alt={course.title}
							fill
							sizes="220.5px"
							className="object-cover"
							unoptimized
						/>
					</div>

					{/* 교육과정 정보 */}
					<div className="basis-0 flex flex-col gap-[12px] grow items-start min-h-px min-w-px relative shrink-0">
						{/* 제목 영역 */}
						<div className="flex gap-[8px] h-[27px] items-center w-full">
							<div className="bg-[#e5f5ec] box-border flex h-[20px] items-center justify-center px-[4px] py-0 rounded-[4px] shrink-0">
								<p className="font-['Pretendard:SemiBold',sans-serif] text-[#0c9d61] text-[13px] leading-[1.4]">{course.status}</p>
							</div>
							<h2 className="font-['Pretendard:SemiBold',sans-serif] text-[#333c47] text-[18px] leading-[1.5]">{course.title}</h2>
						</div>

						{/* 학습 목표 및 방법 */}
						<div className="flex flex-col gap-[4px] items-start w-full">
							<p className="font-['Pretendard:Regular',sans-serif] text-[#333c47] text-[15px] leading-[1.5] mb-0">
								<span className="font-['Pretendard:Medium',sans-serif]">학습 목표:</span>
								<span>{` ${course.goal}`}</span>
							</p>
							<p className="font-['Pretendard:Regular',sans-serif] text-[#333c47] text-[15px] leading-[1.5]">
								<span className="font-['Pretendard:Medium',sans-serif]">학습 방법:</span>
								<span>{` ${course.method}`}</span>
							</p>
						</div>

						{/* 통계 정보 */}
						<div className="flex gap-[4px] items-center w-full">
							<div className="flex gap-[20px] items-center">
								{/* VOD 정보 */}
								<div className="flex gap-[4px] items-center">
									<div className="relative shrink-0 size-[16px]">
										<img src={imgPlay} alt="" className="block max-w-none size-full" />
									</div>
									<p className="font-['Pretendard:Medium',sans-serif] text-[#8c95a1] text-[13px] leading-[1.4]">{course.summary}</p>
								</div>

								{/* 학습 제출 정보 */}
								{course.submitSummary && (
									<div className="flex gap-[4px] items-center">
										<div className="relative shrink-0 size-[16px]">
											<img src={imgMusicAudioPlay} alt="" className="block max-w-none size-full" />
										</div>
										<p className="font-['Pretendard:Medium',sans-serif] text-[#8c95a1] text-[13px] leading-[1.4]">{course.submitSummary}</p>
									</div>
								)}
							</div>
						</div>
					</div>
				</div>

				{/* Lecture 리스트 */}
				<div className="flex flex-col gap-[8px] items-start mt-[24px] w-full">
					{lectures.length > 0 ? (
						lectures.map((lecture: any, index: number) => {
							const lectureId = String(lecture.id || lecture.lectureId);
							const progress = lectureProgresses[lectureId];
							const isCompleted = progress?.isCompleted === true;
							const hasProgress = !!progress;

							// 버튼 텍스트 결정: isCompleted면 "복습하기", progress 있으면 "이어서 수강하기", 없으면 "수강하기"
							const action = isCompleted ? "복습하기" : (hasProgress ? "이어서 수강하기" : "수강하기");

							const isSubmitted = false; // TODO: 학습 제출 상태는 별도로 관리 필요
							const submitBtnBorder = isSubmitted
								? "border-transparent"
								: (action === "이어서 수강하기" || action === "수강하기" ? "border-[#b1b8c0]" : "border-[#8c95a1]");
							const submitBtnText = isSubmitted ? "text-[#384fbf]" : (action === "이어서 수강하기" || action === "수강하기" ? "text-[#b1b8c0]" : "text-[#4c5561]");

							// isCompleted면 배경색 #F1F3F5, 아니면 기본 스타일
							const rightBtnStyle =
								isCompleted
									? "bg-[#f1f3f5] text-[#4c5561]"
									: (action === "이어서 수강하기" || action === "수강하기"
										? "bg-[#ecf0ff] text-[#384fbf]"
										: "bg-[#f1f3f5] text-[#4c5561]");

							return (
								<div key={lecture.id || lecture.lectureId || index} className="bg-white border border-[#dee1e6] border-solid relative rounded-[8px] w-full">
									<div className="box-border flex gap-[16px] items-center overflow-clip px-[24px] py-[16px] rounded-[inherit] w-full">
										<div className="basis-0 flex grow h-[46px] items-center justify-between min-h-px min-w-px relative shrink-0">
											{/* Lecture 정보 */}
											<div className="basis-0 grow min-h-px min-w-px relative shrink-0">
												<div className="flex flex-col gap-[4px] items-start w-full">
													<p className="font-['Pretendard:SemiBold',sans-serif] text-[#333c47] text-[16px] leading-[1.5]">
														{index + 1}. {lecture.title || lecture.lectureName || ''}
													</p>
													<div className="flex gap-[12px] items-center w-full">
														<p className="font-['Pretendard:Medium',sans-serif] text-[#8c95a1] text-[13px] leading-[1.4] w-[40px]">
															{lecture.duration || '00:00'}
														</p>
													</div>
												</div>
											</div>

											{/* 버튼 영역 */}
											<div className="relative shrink-0">
												<div className="flex gap-[8px] items-center">
													{/* 학습 제출 버튼 */}
													<button
														type="button"
														className={[
															"bg-white box-border flex flex-col h-[32px] items-center justify-center px-[16px] py-[3px] rounded-[6px] shrink-0",
															"border border-solid",
															submitBtnBorder,
															submitBtnText,
														].join(" ")}
													>
														{isSubmitted ? (
															<div className="flex gap-[4px] h-[18px] items-center">
																<div className="relative shrink-0 size-[12px]">
																	<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
																		<path d="M10 3L4.5 8.5L2 6" stroke="#384fbf" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
																	</svg>
																</div>
																<p className="font-['Pretendard:Medium',sans-serif] text-[#384fbf] text-[13px] leading-[1.4]">학습 제출 완료</p>
															</div>
														) : (
															<p className={[
																"font-['Pretendard:Medium',sans-serif] text-[14px] leading-[1.5] text-center",
																submitBtnText,
															].join(" ")}>학습 제출 하기</p>
														)}
													</button>

													{/* 수강/복습 버튼 */}
													<button
														type="button"
														onClick={async () => {
															const lectureId = lecture.id || lecture.lectureId;
															if (lectureId) {
																// "수강하기" 버튼 클릭 시 progress 생성
																if (action === "수강하기") {
																	try {
																		await apiService.updateLectureProgress({
																			lectureId: Number(lectureId),
																			progressPct: 0,
																			lastPositionSec: 0,
																		});
																	} catch (error) {
																		console.error('Progress 생성 실패:', error);
																	}
																}
																router.push(`/menu/courses/lessons/${lectureId}/start`);
															}
														}}
														className={[
															"box-border flex flex-col h-[32px] items-center justify-center px-[16px] py-[3px] rounded-[6px] shrink-0 transition-colors",
															rightBtnStyle,
															isCompleted
																? "hover:bg-[#e5e8eb]"
																: (action === "이어서 수강하기" || action === "수강하기"
																	? "hover:bg-[#d0d9ff]"
																	: "hover:bg-[#e5e8eb]"),
														].join(" ")}
													>
														<p className={[
															"font-['Pretendard:Medium',sans-serif] text-[14px] leading-[1.5] text-center",
															isCompleted ? "text-[#4c5561]" : (action === "이어서 수강하기" || action === "수강하기" ? "text-[#384fbf]" : "text-[#4c5561]"),
														].join(" ")}>{action}</p>
													</button>
												</div>
											</div>
										</div>
									</div>
								</div>
							);
						})
					) : (
						<div className="flex items-center justify-center py-8 w-full">
							<p className="text-[14px] text-[#8c95a1]">등록된 강의가 없습니다.</p>
						</div>
					)}
				</div>
			</section>
		</main>
	);
}

