'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import ChevronDownSvg from '../svgs/chevrondownsvg';
import apiService from '../lib/apiService';

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

const imgPlay = '/imgs/play.svg'; // public/imgs/play.svg

interface Subject {
  id: string | number;
  title: string;
  imageKey?: string;
  instructor?: string;
}

interface Course {
  id: string | number;
  title: string;
  image: string;
  inProgress?: boolean;
  meta?: string;
}

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

export default function CourseListPage() {
  const ITEMS_PER_PAGE = 20;
  const [page, setPage] = useState(1);
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);
  const [totalCount, setTotalCount] = useState(0);
  const router = useRouter();

  // 과목 리스트 가져오기
  useEffect(() => {
    let isMounted = true;

    async function fetchSubjects() {
      try {
        setLoading(true);
        const response = await apiService.getSubjects();

        if (response.status !== 200 || !response.data) {
          return;
        }

        // 응답 데이터 구조 확인 및 배열 추출
        let subjectsData: any[] = [];
        let total = 0;

        if (Array.isArray(response.data)) {
          subjectsData = response.data;
          total = response.data.length;
        } else if (response.data && typeof response.data === 'object') {
          // 다양한 응답 구조 처리
          subjectsData = response.data.items || 
                        response.data.courses || 
                        response.data.data || 
                        response.data.list || 
                        response.data.subjects || 
                        response.data.subjectList || 
                        [];
          
          // 전체 개수는 total, totalCount, count 등의 필드에서 가져오거나 배열 길이 사용
          total = response.data.total !== undefined ? response.data.total :
                  response.data.totalCount !== undefined ? response.data.totalCount :
                  response.data.count !== undefined ? response.data.count :
                  subjectsData.length;
        }

        if (!isMounted) return;

        setTotalCount(total);
        setSubjects(subjectsData);

        // 각 과목의 이미지 다운로드
        const coursesWithImages = await Promise.all(
          subjectsData.map(async (subject: Subject) => {
            let imageUrl = 'https://picsum.photos/seed/xrlms-fallback-card/1200/800';
            
            if (subject.imageKey) {
              try {
                const fileUrl = await apiService.getFile(subject.imageKey);
                if (fileUrl) {
                  imageUrl = fileUrl;
                }
              } catch (error) {
                console.error(`이미지 다운로드 실패 (과목 ID: ${subject.id}):`, error);
              }
            }

            return {
              id: subject.id,
              title: subject.title || '',
              image: imageUrl,
              inProgress: false, // TODO: 수강 중 상태는 진행률 API에서 가져와야 함
              meta: subject.instructor ? `강사: ${subject.instructor}` : 'VOD • 온라인',
            };
          })
        );

        if (isMounted) {
          setCourses(coursesWithImages);
        }
      } catch (error) {
        console.error('과목 리스트 조회 오류:', error);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchSubjects();

    return () => {
      isMounted = false;
    };
  }, []);

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

  // 페이지네이션: 10개씩 표시
  const pageGroup = Math.floor((page - 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 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-text-title">교육 과정 목록</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-neutral-700">
            총 <span className="text-primary">{totalCount}</span>건
          </p>
          <div className="h-[40px] w-[114px]" />
        </div>

        {loading ? (
          <div className="mt-4 flex items-center justify-center h-[400px]">
            <p className="text-[16px] font-medium text-[#6C7682]">로딩 중...</p>
          </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}
                    onClick={() => router.push(`/course-list/${c.id}`)}
                    className="flex h-[260px] w-[249.6px] flex-col gap-[16px] rounded-[8px] bg-white cursor-pointer"
                  >
                    {/* 섬네일 */}
                    <div className="relative h-[166.4px] w-full overflow-clip rounded-[8px] flex items-center justify-center bg-[#F1F3F5] hover:shadow-lg transition-shadow">
                      <img
                        src={c.image}
                        alt={c.title}
                        className="h-full w-auto object-contain"
                        onError={(e) => {
                          const t = e.currentTarget as HTMLImageElement;
                          if (!t.src.includes('picsum.photos')) t.src = 'https://picsum.photos/seed/xrlms-fallback-card/1200/800';
                        }}
                      />
                    </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-neutral-700 truncate" title={c.title}>
                          {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-text-meta">
                          {c.meta || 'VOD • 온라인'}
                        </p>
                      </div>
                    </div>
                  </article>
                ))}
              </div>
            </div>

            {/* 페이지네이션 - admin 페이지와 동일한 메커니즘 (10개씩 표시) */}
            {totalCount > ITEMS_PER_PAGE && (
              <div className="mt-8 flex items-center justify-center gap-[8px]">
                {/* First (맨 앞으로) */}
                <button
                  type="button"
                  onClick={() => setPage(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={page === 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={() => setPage((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={page === 1}
                >
                  <ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
                </button>

                {/* Numbers */}
                {visiblePages.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] 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={() => setPage((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={page === totalPages}
                >
                  <ChevronDownSvg width={14.8} height={14.8} className="-rotate-90" />
                </button>

                {/* Last (맨 뒤로) */}
                <button
                  type="button"
                  onClick={() => setPage(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={page === 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>
            )}
          </>
        )}
      </section>
    </main>
  );
}
