'use client';

import { useMemo, useState } from 'react';
import ChevronDownSvg from '../svgs/chevrondownsvg';

// 피그마 선택 컴포넌트의 구조/스타일(타이포/여백/색상)을 반영한 리스트 UI
// - 프로젝트는 Tailwind v4(@import "tailwindcss")를 사용하므로 클래스 그대로 적용
// - 헤더/푸터는 레이아웃에서 처리되므로 본 페이지에는 포함하지 않음
// - 카드 구성: 섬네일(rounded 8px) + 상태 태그 + 제목 + 메타(재생 아이콘 + 텍스트)

const imgPlay = '/imgs/play.svg'; // public/imgs/play.svg
const imgThumbA = '/imgs/thumb-a.png'; // public/imgs/thumb-a.png
const imgThumbB = '/imgs/thumb-b.png'; // public/imgs/thumb-b.png
const imgThumbC = '/imgs/thumb-c.png'; // public/imgs/thumb-c.png
const imgThumbD = '/imgs/thumb-d.png'; // public/imgs/thumb-d.png

function ColorfulTag({ text }: { text: string }) {
  return (
    <div className="bg-[#e5f5ec] box-border flex h-[20px] items-center justify-center px-[4px] rounded-[4px]">
      <p className="font-['Pretendard:SemiBold',sans-serif] text-[#0c9d61] text-[13px] leading-[1.4]">{text}</p>
    </div>
  );
}

type Course = { id: string; title: string; image: string; inProgress?: boolean };

export default function CourseListPage() {
  const ITEMS_PER_PAGE = 20;
  const [page, setPage] = useState(1);

  const base: Omit<Course, 'id'>[] = [
    { title: '원자로 운전 및 계통', image: imgThumbA, inProgress: true },
    { title: '핵연료', image: imgThumbB },
    { title: '방사선 안전', image: imgThumbC },
    { title: '방사선 폐기물', image: imgThumbD },
    { title: '원자로 운전 및 계통', image: imgThumbA },
    { title: '핵연료', image: imgThumbB },
    { title: '방사선 안전', image: imgThumbC },
  ];
  const courses: Course[] = Array.from({ length: 28 }, (_, i) => {
    const item = base[i % base.length];
    return {
      id: `p${i + 1}`,
      title: item.title,
      image: item.image,
      inProgress: item.inProgress ?? (i % 7 === 0),
    };
  });
  const totalPages = Math.ceil(courses.length / ITEMS_PER_PAGE);
  const pagedCourses = useMemo(
    () => courses.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE),
    [courses, page]
  );

  return (
    <main className="flex w-full flex-col items-center">
      {/* 상단 타이틀 영역 */}
      <div className="flex h-[100px] w-full max-w-[1440px] items-center px-8">
        <h1 className="text-[24px] font-bold leading-normal text-[#1b2027]">교육 과정 목록</h1>
      </div>

      {/* 콘텐츠 래퍼: Figma 기준 1440 컨테이너, 내부 1376 그리드 폭 */}
      <section className="w-full max-w-[1440px] px-8 pt-8 pb-20">
        {/* 상단 카운트/정렬 영역 */}
        <div className="flex items-center justify-between">
          <p className="text-[15px] font-medium leading-normal text-[#333c47]">
            총 <span className="text-[#384fbf]">{courses.length}</span>건
          </p>
          <div className="h-[40px] w-[114px]" />
        </div>

        {/* 카드 그리드(고정 5열, gap 32px) */}
        <div className="mt-4 flex flex-col items-center">
          <div className="w-[1376px] grid grid-cols-5 gap-[32px]">
            {pagedCourses.map((c) => (
              <article
                key={c.id}
                className="flex h-[260px] w-[249.6px] flex-col gap-[16px] rounded-[8px] bg-white"
              >
                {/* 섬네일 */}
                <div className="relative h-[166.4px] w-full overflow-clip rounded-[8px]">
                  <img
                    src={c.image}
                    alt=""
                    className="absolute inset-0 size-full object-cover"
                  />
                </div>

                {/* 본문 텍스트 블록 */}
                <div className="flex w-full flex-col gap-[4px]">
                  <div className="flex flex-col gap-[4px]">
                    {c.inProgress && <ColorfulTag text="수강 중" />}
                    <h2 className="text-[18px] font-semibold leading-normal text-[#333c47]">
                      {c.title}
                    </h2>
                  </div>
                  <div className="flex items-center gap-[4px]">
                    <img src={imgPlay} alt="" className="size-[16px]" />
                    <p className="text-[13px] font-medium leading-[1.4] text-[#8c95a1]">
                      VOD · 총 6강 · 4시간 20분
                    </p>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </div>

        {/* 페이지네이션 (피그마 스타일 반영) */}
        <div className="mt-8 flex items-center justify-center gap-[8px]">
          {/* Prev */}
          <button
            type="button"
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            aria-label="이전 페이지"
            className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40"
            disabled={page === 1}
          >
            <ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
          </button>

          {/* Numbers */}
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((n) => {
            const active = n === page;
            return (
              <button
                key={n}
                type="button"
                onClick={() => setPage(n)}
                aria-current={active ? 'page' : undefined}
                className={[
                  'flex items-center justify-center rounded-[1000px] size-[32px]',
                  active ? 'bg-[#ecf0ff]' : 'bg-white',
                ].join(' ')}
              >
                <span className="text-[16px] leading-[1.4] text-[#333c47]">{n}</span>
              </button>
            );
          })}

          {/* Next */}
          <button
            type="button"
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            aria-label="다음 페이지"
            className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40"
            disabled={page === totalPages}
          >
            <ChevronDownSvg width={14.8} height={14.8} className="-rotate-90" />
          </button>
        </div>
      </section>
    </main>
  );
}


