'use client';

import Image from "next/image";
import { useRouter } from "next/navigation";
import { useState } from "react";
import ChevronDownSvg from "../../svgs/chevrondownsvg";

type Lesson = {
	id: string;
	title: string;
	durationMin: number;
	progressPct: number; // 0~100
	isCompleted: boolean;
};

type Course = {
	id: string;
	title: string;
	description: string;
	thumbnail: string;
	status: "전체" | "수강 예정" | "수강중" | "수강 완료";
	progressPct: number;
	lessons: Lesson[];
};

function ProgressBar({ value }: { value: number }) {
	const pct = Math.max(0, Math.min(100, value));
	return (
		<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-bg-primary-light">
			<div
				className="h-full rounded-full bg-primary transition-[width] duration-300 ease-out"
				style={{ width: `${pct}%` }}
			/>
		</div>
	);
}

export default function CourseCard({ course, defaultOpen = false }: { course: Course; defaultOpen?: boolean }) {
	const [open, setOpen] = useState(defaultOpen);
	const router = useRouter();

	const totalMinutes = course.lessons.reduce((sum, l) => sum + (l.durationMin || 0), 0);
	const totalHours = Math.floor(totalMinutes / 60);
	const restMinutes = totalMinutes % 60;
	const firstIncomplete = course.lessons.find((l) => !l.isCompleted)?.id;
	const cardClassName = [
		"rounded-xl bg-white shadow-[0_2px_8px_rgba(0,0,0,0.02)]",
		open ? "border-[3px] border-primary" : "border border-bg-primary-light",
	].join(" ");

	const formatDuration = (m: number) => {
		const minutes = String(m).padStart(2, "0");
		const seconds = String((m * 7) % 60).padStart(2, "0");
		return `${minutes}:${seconds}`;
	};

	return (
		<article className={cardClassName}>
			<header className="flex items-center gap-6 px-8 py-6">
				<div className="relative h-[120px] w-[180px] overflow-hidden rounded-[8px] bg-bg-gray-light">
					<Image
						src={`https://picsum.photos/seed/${encodeURIComponent(course.id)}/240/152`}
						alt=""
						fill
						sizes="180px"
						unoptimized
						className="object-cover"
					/>
				</div>
				<div className="min-w-0 flex-1">
					<div className="flex items-center gap-2">
						<span className="flex h-[20px] items-center justify-center rounded-[4px] bg-bg-success-light px-[4px] text-[13px] font-semibold leading-[1.4] text-success">
							{course.status}
						</span>
						<h2 className="truncate text-[18px] font-semibold leading-normal text-neutral-700">
							{course.title}
						</h2>
					</div>
					<p className="mt-1 line-clamp-2 text-[14px] leading-normal text-basic-text">{course.description}</p>
					<div className="mt-2 flex items-center justify-between gap-3">
						<p className="text-[13px] leading-[1.4] text-text-meta">
							VOD · 총 {course.lessons.length}강 · {totalHours}시간 {restMinutes}분
						</p>
						<p className="text-[13px] font-semibold leading-[1.4] text-primary">
							전체 진도율: {course.progressPct}%
						</p>
					</div>
					<div className="mt-2">
						<ProgressBar value={course.progressPct} />
					</div>
				</div>
				<div className="flex items-center gap-2 self-start">
					<button
						type="button"
						aria-expanded={open}
						onClick={() => setOpen((v) => !v)}
						className="flex h-8 w-8 items-center justify-center text-text-label cursor-pointer"
						aria-label={open ? "접기" : "펼치기"}
					>
						<ChevronDownSvg
							width={16}
							height={16}
							className={["transition-transform", open ? "rotate-180" : "rotate-0"].join(" ")}
						/>
					</button>
				</div>
			</header>

			{open ? (
				<div className="px-6 pb-6">
					<ul className="flex flex-col gap-2">
						{course.lessons.map((lesson, idx) => (
							<li key={lesson.id} className="rounded-lg border border-input-border bg-white">
								<div className="flex items-center justify-between gap-4 px-[24px] py-[16px]">
									<div className="min-w-0 flex-1">
										<p className="truncate text-[16px] font-semibold leading-normal text-neutral-700">
											{`${idx + 1}. ${lesson.title}`}
										</p>
										<div className="mt-2 flex items-center gap-3">
											<span className="text-[13px] leading-[1.4] text-text-meta">
												{formatDuration(lesson.durationMin)}
											</span>
										</div>
									</div>
									<div className="flex items-center gap-2">
										<button
											type="button"
											className={[
												"inline-flex h-[32px] w-[140px] items-center justify-center gap-[6px] rounded-[6px] px-4 text-center whitespace-nowrap cursor-pointer",
												lesson.isCompleted
													? "bg-white text-[13px] font-medium leading-[1.4] text-primary"
													: "bg-white text-[14px] font-medium leading-normal text-basic-text border border-text-meta",
											].join(" ")}
										>
											{lesson.isCompleted ? (
												<>
													<svg
														xmlns="http://www.w3.org/2000/svg"
														width="10"
														height="7"
														viewBox="0 0 10 7"
														fill="none"
														aria-hidden
													>
														<path
															d="M8.75 0.75L3.25 6.25L0.75 3.75"
															stroke="var(--color-primary)"
															strokeWidth="1.5"
															strokeLinecap="round"
															strokeLinejoin="round"
														/>
													</svg>
													<span>학습 제출 완료</span>
												</>
											) : (
												"학습 제출 하기"
											)}
										</button>
										{lesson.isCompleted ? (
											<button
												type="button"
												onClick={() => router.push(`/menu/courses/lessons/${lesson.id}/review`)}
												className="inline-flex h-[32px] w-[140px] items-center justify-center rounded-[6px] bg-bg-gray-light px-4 text-center text-[14px] font-medium leading-normal text-basic-text whitespace-nowrap cursor-pointer"
											>
												복습하기
											</button>
										) : (
											<button
												type="button"
												onClick={() =>
													router.push(
														lesson.id === firstIncomplete
															? `/menu/courses/lessons/${lesson.id}/continue`
															: `/menu/courses/lessons/${lesson.id}/start`,
													)
												}
												className={[
													"inline-flex h-[32px] w-[140px] items-center justify-center rounded-[6px] px-4 text-center text-[14px] font-medium leading-normal whitespace-nowrap cursor-pointer",
													lesson.id === firstIncomplete
														? "bg-bg-primary-light text-primary"
														: "border border-input-border text-basic-text",
												].join(" ")}
											>
												{lesson.id === firstIncomplete ? "이어서 수강하기" : "수강하기"}
											</button>
										)}
									</div>
								</div>
							</li>
						))}
					</ul>
				</div>
			) : null}
		</article>
	);
}


