'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import PaperClipSvg from '../svgs/paperclipsvg';
import ChevronDownSvg from '../svgs/chevrondownsvg';
import apiService from '../lib/apiService';
import type { Resource } from '../admin/resources/mockData';

export default function ResourcesPage() {
  const router = useRouter();
  const [resources, setResources] = useState<Resource[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);

  // 날짜를 yyyy-mm-dd 형식으로 포맷팅
  const formatDate = (dateString: string): string => {
    if (!dateString) return '';
    
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        // 이미 yyyy-mm-dd 형식인 경우 그대로 반환
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
          return dateString;
        }
        return dateString;
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch {
      return dateString;
    }
  };

  // API에서 학습 자료 목록 가져오기
  useEffect(() => {
    async function fetchResources() {
      try {
        setIsLoading(true);
        const response = await apiService.getLibrary();
        const data = response.data;
        
        // API 응답이 배열이 아닌 경우 처리 (예: { items: [...] } 형태)
        let resourcesArray: any[] = [];
        if (Array.isArray(data)) {
          resourcesArray = data;
        } else if (data && typeof data === 'object') {
          resourcesArray = data.items || data.resources || data.data || data.list || [];
        }
        
        // API 응답 데이터를 Resource 형식으로 변환
        const transformedResources: Resource[] = resourcesArray.map((resource: any) => ({
          id: resource.id || resource.resourceId || 0,
          title: resource.title || '',
          date: resource.date || resource.createdAt || resource.createdDate || new Date().toISOString().split('T')[0],
          views: resource.views || resource.viewCount || 0,
          writer: resource.writer || resource.author || resource.createdBy || '관리자',
          content: resource.content ? (Array.isArray(resource.content) ? resource.content : [resource.content]) : undefined,
          hasAttachment: resource.hasAttachment || resource.attachment || false,
        }));
        
        setResources(transformedResources);
      } catch (error) {
        console.error('학습 자료 목록 조회 오류:', error);
        // 에러 발생 시 빈 배열로 설정
        setResources([]);
      } finally {
        setIsLoading(false);
      }
    }
    
    fetchResources();
  }, []);

  const totalCount = useMemo(() => resources.length, [resources]);

  const ITEMS_PER_PAGE = 10;
  const sortedResources = useMemo(() => {
    return [...resources].sort((a, b) => {
      // 생성일 내림차순 정렬 (최신 날짜가 먼저)
      return b.date.localeCompare(a.date);
    });
  }, [resources]);

  const totalPages = Math.ceil(sortedResources.length / ITEMS_PER_PAGE);
  const paginatedResources = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    return sortedResources.slice(startIndex, endIndex);
  }, [sortedResources, currentPage]);

  return (
    <div className="w-full bg-white">
      <div className="flex justify-center">
        <div className="w-full max-w-[1440px]">
          {/* 헤더 영역 */}
          <div className="h-[100px] flex items-center px-8">
            <h1 className="m-0 text-[24px] font-bold leading-[1.5] text-[#1B2027]">
              학습 자료실
            </h1>
          </div>

          {/* 본문 영역 */}
          <section className="px-8 pb-8">
            {/* 총 건수 */}
            <div className="h-10 flex items-center">
              <p className="m-0 text-[15px] font-medium leading-[1.5] text-[#333C47]">
                총 <span className="text-[#384FBF]">{totalCount}</span>건
              </p>
            </div>

            {isLoading ? (
              <div className="rounded-[8px] border border-[#DEE1E6] bg-white min-h-[400px] flex items-center justify-center">
                <p className="text-[16px] font-medium leading-[1.5] text-[#333C47]">
                  로딩 중...
                </p>
              </div>
            ) : resources.length === 0 ? (
              <div className="rounded-[8px] border border-[#DEE1E6] bg-white min-h-[400px] flex items-center justify-center">
                <p className="text-[16px] font-medium leading-[1.5] text-[#333C47] text-center">
                  등록된 학습 자료가 없습니다.
                </p>
              </div>
            ) : (
              <>
                {/* 표 */}
                <div className="rounded-[8px] border border-[#DEE1E6] overflow-hidden bg-white">
                  {/* 헤더 */}
                  <div className="grid grid-cols-[80px_1fr_140px_120px_120px] bg-[#F9FAFB] h-[48px] text-[14px] font-semibold text-[#4C5561] border-b border-[#DEE1E6]">
                    <div className="flex items-center justify-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                      번호
                    </div>
                    <div className="flex items-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                      제목
                    </div>
                    <div className="flex items-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                      게시일
                    </div>
                    <div className="flex items-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                      조회수
                    </div>
                    <div className="flex items-center px-4 whitespace-nowrap">작성자</div>
                  </div>

                  {/* 바디 */}
                  <div>
                    {paginatedResources.map((resource, index) => {
                      // 번호는 전체 목록에서의 순서 (정렬된 목록 기준)
                      const resourceNumber = sortedResources.length - (currentPage - 1) * ITEMS_PER_PAGE - index;
                      return (
                        <div
                          key={resource.id}
                          role="button"
                          tabIndex={0}
                          onClick={() => router.push(`/resources/${resource.id}`)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                              e.preventDefault();
                              router.push(`/resources/${resource.id}`);
                            }
                          }}
                          className={[
                            'grid grid-cols-[80px_1fr_140px_120px_120px] h-[48px] text-[13px] font-medium text-[#1B2027] border-t border-[#DEE1E6] hover:bg-[rgba(236,240,255,0.5)] cursor-pointer',
                          ].join(' ')}
                        >
                          <div className="flex items-center justify-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                            {resourceNumber}
                          </div>
                          <div
                            className="flex items-center gap-1.5 px-4 border-r border-[#DEE1E6] whitespace-nowrap overflow-hidden text-ellipsis"
                            title={resource.title}
                          >
                            {resource.title}
                            {resource.hasAttachment && (
                              <PaperClipSvg width={16} height={16} className="shrink-0 text-[#8C95A1]" />
                            )}
                          </div>
                          <div className="flex items-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                            {formatDate(resource.date)}
                          </div>
                          <div className="flex items-center px-4 border-r border-[#DEE1E6] whitespace-nowrap">
                            {resource.views.toLocaleString()}
                          </div>
                          <div className="flex items-center px-4 whitespace-nowrap">{resource.writer}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* 페이지네이션 - 10개 초과일 때만 표시 */}
                {resources.length > ITEMS_PER_PAGE && (
                  <div className="pt-8 pb-[32px] 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-[#333c47] 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-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
                        disabled={currentPage === 1}
                      >
                        <ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
                      </button>

                      {/* Numbers */}
                      {(() => {
                        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 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-[#ecf0ff]' : 'bg-white',
                              ].join(' ')}
                            >
                              <span className="text-[16px] leading-[1.4] text-[#333c47]">{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-[#333c47] 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-[#333c47] 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>
                )}
              </>
            )}
          </section>
        </div>
      </div>
    </div>
  );
}


