'use client';

import { useState, useMemo, useRef, useEffect } from "react";
import AdminSidebar from "@/app/components/AdminSidebar";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
import DropdownIcon from "@/app/svgs/dropdownicon";
import BackArrowSvg from "@/app/svgs/backarrow";
import { MOCK_COURSES } from "@/app/admin/courses/mockData";

export default function AdminLessonsPage() {
  // TODO: 나중에 실제 데이터로 교체
  const items: any[] = [];
  const [currentPage, setCurrentPage] = useState(1);
  const [isRegistrationMode, setIsRegistrationMode] = useState(false);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  // 등록 폼 상태
  const [selectedCourse, setSelectedCourse] = useState<string>("");
  const [lessonName, setLessonName] = useState("");
  const [learningGoal, setLearningGoal] = useState("");
  const [courseVideoCount, setCourseVideoCount] = useState(0);
  const [vrContentCount, setVrContentCount] = useState(0);
  
  const totalCount = useMemo(() => items.length, [items]);
  
  const ITEMS_PER_PAGE = 10;
  const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
  const paginatedItems = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    const endIndex = startIndex + ITEMS_PER_PAGE;
    return items.slice(startIndex, endIndex);
  }, [items, currentPage]);

  // 교육과정 옵션 - mockData에서 가져오기
  const courseOptions = useMemo(() => 
    MOCK_COURSES.map(course => ({ 
      id: course.id, 
      name: course.courseName 
    }))
  , []);

  // 외부 클릭 시 드롭다운 닫기
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
    };

    if (isDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isDropdownOpen]);

  const handleBackClick = () => {
    setIsRegistrationMode(false);
    // 폼 초기화
    setSelectedCourse("");
    setLessonName("");
    setLearningGoal("");
    setCourseVideoCount(0);
    setVrContentCount(0);
  };

  const handleRegisterClick = () => {
    setIsRegistrationMode(true);
  };

  return (
    <div className="min-h-screen flex flex-col bg-white">
      {/* 메인 레이아웃 */}
      <div className="flex flex-1 min-h-0 justify-center">
        <div className="w-[1440px] flex min-h-0">
          {/* 사이드바 */}
          <div className="flex">
            <AdminSidebar />
          </div>
          {/* 메인 콘텐츠 */}
          <main className="w-[1120px] bg-white">
            <div className="h-full flex flex-col px-8">
              {isRegistrationMode ? (
                /* 등록 모드 */
                <div className="flex flex-col h-full">
                  {/* 헤더 */}
                  <div className="h-[100px] flex items-center">
                    <div className="flex items-center gap-[12px]">
                      <button
                        type="button"
                        onClick={handleBackClick}
                        className="flex items-center justify-center size-[32px] cursor-pointer hover:opacity-80"
                        aria-label="뒤로가기"
                      >
                        <BackArrowSvg width={32} height={32} />
                      </button>
                      <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
                        강좌 등록
                      </h1>
                    </div>
                  </div>

                  {/* 폼 콘텐츠 */}
                  <div className="flex-1 overflow-y-auto pb-[80px] pt-[32px]">
                    <div className="flex flex-col gap-[40px]">
                      {/* 강좌 정보 */}
                      <div className="flex flex-col gap-[8px]">
                        <h2 className="text-[18px] font-bold leading-[1.5] text-[#1b2027]">
                          강좌 정보
                        </h2>
                        <div className="flex flex-col gap-[24px]">
                          {/* 교육 과정 */}
                          <div className="flex flex-col gap-[8px] max-w-[480px]">
                            <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                              교육 과정
                            </label>
                            <div className="relative" ref={dropdownRef}>
                              <button
                                type="button"
                                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                className="w-full h-[40px] px-[12px] py-[8px] border border-[#dee1e6] rounded-[8px] bg-white flex items-center justify-between focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent cursor-pointer"
                              >
                                <span className={`text-[16px] font-normal leading-[1.5] flex-1 text-left ${
                                  selectedCourse ? 'text-[#1b2027]' : 'text-[#6c7682]'
                                }`}>
                                  {selectedCourse 
                                    ? courseOptions.find(c => c.id === selectedCourse)?.name 
                                    : '교육과정을 선택해 주세요.'}
                                </span>
                                <DropdownIcon stroke="#8C95A1" className="shrink-0" />
                              </button>
                              {isDropdownOpen && (
                                <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-[#dee1e6] rounded-[8px] shadow-lg z-20 max-h-[200px] overflow-y-auto">
                                  {courseOptions.map((course, index) => (
                                    <button
                                      key={course.id}
                                      type="button"
                                      onClick={() => {
                                        setSelectedCourse(course.id);
                                        setIsDropdownOpen(false);
                                      }}
                                      className={`w-full px-3 py-2 text-left text-[16px] font-normal leading-[1.5] hover:bg-[#f1f3f5] transition-colors cursor-pointer ${
                                        selectedCourse === course.id
                                          ? "bg-[#ecf0ff] text-[#1f2b91] font-semibold"
                                          : "text-[#1b2027]"
                                      } ${
                                        index === 0 ? "rounded-t-[8px]" : ""
                                      } ${
                                        index === courseOptions.length - 1 ? "rounded-b-[8px]" : ""
                                      }`}
                                    >
                                      {course.name}
                                    </button>
                                  ))}
                                </div>
                              )}
                            </div>
                          </div>

                          {/* 강좌명 */}
                          <div className="flex flex-col gap-[8px]">
                            <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                              강좌명
                            </label>
                            <input
                              type="text"
                              value={lessonName}
                              onChange={(e) => setLessonName(e.target.value)}
                              placeholder="강좌명을 입력해 주세요."
                              className="h-[40px] px-[12px] py-[8px] border border-[#dee1e6] rounded-[8px] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
                            />
                          </div>

                          {/* 학습 목표 */}
                          <div className="flex flex-col gap-[8px]">
                            <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                              학습 목표
                            </label>
                            <div className="relative">
                              <textarea
                                value={learningGoal}
                                onChange={(e) => {
                                  if (e.target.value.length <= 1000) {
                                    setLearningGoal(e.target.value);
                                  }
                                }}
                                placeholder="내용을 입력해 주세요. (최대 1,000자)"
                                className="w-full h-[160px] px-[12px] py-[8px] border border-[#dee1e6] rounded-[8px] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent resize-none"
                              />
                              <div className="absolute bottom-[8px] right-[12px]">
                                <p className="text-[13px] font-normal leading-[1.4] text-[#6c7682] text-right">
                                  {learningGoal.length}/1000
                                </p>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 파일 첨부 */}
                      <div className="flex flex-col gap-[8px]">
                        <h2 className="text-[18px] font-bold leading-[1.5] text-[#1b2027]">
                          파일 첨부
                        </h2>
                        <div className="flex flex-col gap-[24px]">
                          {/* 강좌 영상 */}
                          <div className="flex flex-col gap-[8px]">
                            <div className="flex items-center justify-between h-[32px]">
                              <div className="flex items-center gap-[8px]">
                                <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                                  강좌 영상 ({courseVideoCount}/10)
                                </label>
                                <span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
                                  30MB 미만 파일
                                </span>
                              </div>
                              <button
                                type="button"
                                className="h-[32px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer"
                              >
                                첨부
                              </button>
                            </div>
                            <div className="h-[64px] border border-[#dee1e6] rounded-[8px] bg-gray-50 flex items-center justify-center">
                              <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
                                강좌 주제별 영상 파일을 첨부해주세요.
                              </p>
                            </div>
                          </div>

                          {/* VR 콘텐츠 */}
                          <div className="flex flex-col gap-[8px]">
                            <div className="flex items-center justify-between h-[32px]">
                              <div className="flex items-center gap-[8px]">
                                <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                                  VR 콘텐츠 <span className="font-normal">({vrContentCount}/10)</span>
                                </label>
                                <span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
                                  30MB 미만 파일
                                </span>
                              </div>
                              <button
                                type="button"
                                className="h-[32px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer"
                              >
                                첨부
                              </button>
                            </div>
                            <div className="h-[64px] border border-[#dee1e6] rounded-[8px] bg-gray-50 flex items-center justify-center">
                              <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
                                VR 학습 체험용 콘텐츠 파일을 첨부해주세요.
                              </p>
                            </div>
                          </div>

                          {/* 학습 평가 문제 */}
                          <div className="flex flex-col gap-[8px]">
                            <div className="flex items-center justify-between h-[32px]">
                              <div className="flex items-center gap-[8px]">
                                <label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
                                  학습 평가 문제
                                </label>
                                <span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
                                  CSV 파일 형식만 첨부 가능
                                </span>
                              </div>
                              <div className="flex items-center gap-[8px]">
                                <button
                                  type="button"
                                  className="h-[32px] px-[16px] py-[3px] border border-[#b1b8c0] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#b1b8c0] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer"
                                >
                                  다운로드
                                </button>
                                <button
                                  type="button"
                                  className="h-[32px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer"
                                >
                                  첨부
                                </button>
                              </div>
                            </div>
                            <div className="h-[64px] border border-[#dee1e6] rounded-[8px] bg-gray-50 flex items-center justify-center">
                              <p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
                                학습 평가용 문항 파일을 첨부해주세요.
                              </p>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* 액션 버튼 */}
                      <div className="flex items-center justify-center gap-[12px]">
                        <button
                          type="button"
                          onClick={handleBackClick}
                          className="h-[48px] px-[8px] rounded-[10px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] min-w-[80px] hover:bg-[#e5e7eb] transition-colors cursor-pointer"
                        >
                          취소
                        </button>
                        <button
                          type="button"
                          className="h-[48px] px-[16px] rounded-[10px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white hover:bg-[#1a2478] transition-colors cursor-pointer"
                        >
                          저장하기
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                /* 목록 모드 */
                <>
                  {/* 제목 영역 */}
                  <div className="h-[100px] flex items-center">
                    <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
                      강좌 관리
                    </h1>
                  </div>

                  {/* 헤더 영역 (제목과 콘텐츠 사이) */}
                  <div className="pt-2 pb-4 flex items-center justify-between">
                    <p className="text-[15px] font-medium leading-[1.5] text-[#333c47] whitespace-nowrap">
                      총 {totalCount}건
                    </p>
                    <button
                      type="button"
                      onClick={handleRegisterClick}
                      className="h-[40px] px-4 rounded-[8px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer"
                    >
                      등록하기
                    </button>
                  </div>

                  {/* 콘텐츠 영역 */}
                  <div className="flex-1 pt-2 flex flex-col">
                    {items.length === 0 ? (
                      <div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
                        <p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
                          등록된 강좌가 없습니다.
                          <br />
                          강좌를 등록해주세요.
                        </p>
                      </div>
                    ) : (
                      <>
                        {/* TODO: 테이블 또는 리스트를 여기에 추가 */}
                        
                        {/* 페이지네이션 - 10개 초과일 때만 표시 */}
                        {items.length > ITEMS_PER_PAGE && (() => {
                          // 페이지 번호를 10단위로 표시
                          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 (
                            <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 */}
                                {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>
                          );
                        })()}
                      </>
                    )}
                  </div>
                </>
              )}
            </div>
          </main>
        </div>
      </div>
    </div>
  );
}

