'use client';

import { useState, useEffect, useRef, useMemo } from "react";
import AdminSidebar from "@/app/components/AdminSidebar";
import DropdownIcon from "@/app/svgs/dropdownicon";
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
import { mockUsers, type UserRow } from "./mockData";

type TabType = 'all' | 'learner' | 'instructor' | 'admin';
type RoleType = 'learner' | 'instructor' | 'admin';
type AccountStatus = 'active' | 'inactive';


const roleLabels: Record<RoleType, string> = {
  learner: '학습자',
  instructor: '강사',
  admin: '관리자',
};

const statusLabels: Record<AccountStatus, string> = {
  active: '활성화',
  inactive: '비활성화',
};

export default function AdminIdPage() {
  const [activeTab, setActiveTab] = useState<TabType>('all');
  const [users, setUsers] = useState<UserRow[]>(mockUsers);
  const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);
  const [isActivateModalOpen, setIsActivateModalOpen] = useState(false);
  const [isDeactivateModalOpen, setIsDeactivateModalOpen] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  const ITEMS_PER_PAGE = 10;

  const filteredUsers = useMemo(() => {
    return activeTab === 'all' 
      ? users 
      : users.filter(user => user.role === activeTab);
  }, [activeTab, users]);

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

  // 탭 변경 시 첫 페이지로 리셋
  useEffect(() => {
    setCurrentPage(1);
  }, [activeTab]);

  // 외부 클릭 시 드롭다운 닫기
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (openDropdownId) {
        const dropdownElement = dropdownRefs.current[openDropdownId];
        if (dropdownElement && !dropdownElement.contains(event.target as Node)) {
          setOpenDropdownId(null);
        }
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [openDropdownId]);

  function openActivateModal(userId: string) {
    setSelectedUserId(userId);
    setIsActivateModalOpen(true);
  }

  function handleActivateConfirm() {
    if (selectedUserId) {
      setUsers(prevUsers => 
        prevUsers.map(user => 
          user.id === selectedUserId 
            ? { ...user, status: 'active' }
            : user
        )
      );
      setToastMessage('계정을 활성화했습니다.');
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
    }
    setIsActivateModalOpen(false);
    setSelectedUserId(null);
  }

  function handleActivateCancel() {
    setIsActivateModalOpen(false);
    setSelectedUserId(null);
  }

  function openDeactivateModal(userId: string) {
    setSelectedUserId(userId);
    setIsDeactivateModalOpen(true);
  }

  function handleDeactivateConfirm() {
    if (selectedUserId) {
      setUsers(prevUsers => 
        prevUsers.map(user => 
          user.id === selectedUserId 
            ? { ...user, status: 'inactive' }
            : user
        )
      );
      setToastMessage('계정을 비활성화했습니다.');
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
    }
    setIsDeactivateModalOpen(false);
    setSelectedUserId(null);
  }

  function handleDeactivateCancel() {
    setIsDeactivateModalOpen(false);
    setSelectedUserId(null);
  }

  function toggleAccountStatus(userId: string) {
    const user = users.find(u => u.id === userId);
    if (user && user.status === 'inactive') {
      openActivateModal(userId);
    } else if (user && user.status === 'active') {
      openDeactivateModal(userId);
    }
  }

  function toggleDropdown(userId: string) {
    setOpenDropdownId(openDropdownId === userId ? null : userId);
  }

  function changeUserRole(userId: string, newRole: RoleType) {
    setUsers(prevUsers => 
      prevUsers.map(user => 
        user.id === userId 
          ? { ...user, role: newRole }
          : user
      )
    );
    setOpenDropdownId(null);
  }

  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">
            {/* 제목 영역 */}
            <div className="h-[100px] flex items-center">
              <h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
                권한 설정
              </h1>
            </div>
            {/* 탭 네비게이션 */}
            <div>
              <div className="flex items-center gap-8 border-b border-[#dee1e6]">
                {[
                  { id: 'all' as TabType, label: '전체' },
                  { id: 'learner' as TabType, label: '학습자' },
                  { id: 'instructor' as TabType, label: '강사' },
                  { id: 'admin' as TabType, label: '관리자' },
                ].map((tab) => (
                  <button
                    key={tab.id}
                    type="button"
                    onClick={() => setActiveTab(tab.id)}
                    className={[
                      "pb-4 px-1 text-[16px] font-medium leading-[1.5] transition-colors relative cursor-pointer",
                      activeTab === tab.id
                        ? "text-[#1f2b91] font-semibold"
                        : "text-[#6c7682]",
                    ].join(" ")}
                  >
                    {tab.label}
                    {activeTab === tab.id && (
                      <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#1f2b91]" />
                    )}
                  </button>
                ))}
              </div>
            </div>

            {/* 콘텐츠 영역 */}
            <div className="flex-1 pt-8 flex flex-col">
              {filteredUsers.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]">
                    현재 관리할 수 있는 회원 계정이 없습니다.
                  </p>
                </div>
              ) : (
                <>
                  <div className="rounded-[8px]">
                    <div className="w-full rounded-[8px] border border-[#dee1e6] overflow-visible">
                      <table className="min-w-full border-collapse">
                        <colgroup>
                          <col style={{ width: 140 }} />
                          <col />
                          <col />
                          <col style={{ width: 120 }} />
                          <col style={{ width: 120 }} />
                          <col style={{ width: 120 }} />
                        </colgroup>
                        <thead>
                          <tr className="h-12 bg-gray-50 text-left">
                            <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">가입일</th>
                            <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">성명</th>
                            <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">아이디(이메일)</th>
                            <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">권한설정</th>
                            <th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">계정상태</th>
                            <th className="px-4 text-center text-[14px] font-semibold leading-[1.5] text-[#4c5561]">계정관리</th>
                          </tr>
                        </thead>
                        <tbody>
                          {paginatedUsers.map((user) => (
                          <tr
                            key={user.id}
                            className="h-12"
                          >
                            <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              {user.joinDate}
                            </td>
                            <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              {user.name}
                            </td>
                            <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              {user.email}
                            </td>
                            <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              <div className="relative flex items-center justify-between">
                                <span>{roleLabels[user.role]}</span>
                                <div 
                                  ref={(el) => { dropdownRefs.current[user.id] = el; }}
                                  className="relative"
                                >
                                  <button
                                    type="button"
                                    onClick={() => toggleDropdown(user.id)}
                                    className="ml-2 flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity"
                                  >
                                    <DropdownIcon width={16} height={16} stroke="#8C95A1" />
                                  </button>
                                  {openDropdownId === user.id && (
                                    <div className="absolute right-0 top-full mt-1 z-[100] min-w-[120px] bg-white border border-[#dee1e6] rounded-[4px] shadow-lg flex flex-col">
                                      {(['learner', 'instructor', 'admin'] as RoleType[]).map((role) => (
                                        <button
                                          key={role}
                                          type="button"
                                          onClick={() => changeUserRole(user.id, role)}
                                          className={[
                                            "w-full px-4 py-2 text-left text-[14px] leading-[1.5] hover:bg-gray-50 transition-colors cursor-pointer",
                                            user.role === role 
                                              ? "text-[#1f2b91] font-semibold bg-[#ecf0ff]" 
                                              : "text-[#1b2027]",
                                            role !== 'admin' && "border-b border-[#dee1e6]"
                                          ].join(" ")}
                                        >
                                          {roleLabels[role]}
                                        </button>
                                      ))}
                                    </div>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              {user.status === 'active' ? (
                                <div className="inline-flex items-center justify-center h-[20px] px-[4px] rounded-[4px] bg-[#ecf0ff]">
                                  <span className="text-[13px] font-semibold leading-[1.4] text-[#384fbf] whitespace-nowrap">
                                    {statusLabels[user.status]}
                                  </span>
                                </div>
                              ) : (
                                <div className="inline-flex items-center justify-center h-[20px] px-[4px] rounded-[4px] bg-[#f1f3f5]">
                                  <span className="text-[13px] font-semibold leading-[1.4] text-[#4c5561] whitespace-nowrap">
                                    {statusLabels[user.status]}
                                  </span>
                                </div>
                              )}
                            </td>
                            <td className="border-t border-[#dee1e6] px-4 text-center text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
                              <button
                                type="button"
                                onClick={() => toggleAccountStatus(user.id)}
                                className="text-[12px] text-blue-500 underline underline-offset-[3px] cursor-pointer whitespace-nowrap hover:opacity-80"
                              >
                                {user.status === 'active' ? '비활성화 처리' : '활성화 처리'}
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>

                {/* 페이지네이션 - 10개 초과일 때만 표시 */}
                {filteredUsers.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>

      {/* 활성화 확인 모달 */}
      {isActivateModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div 
            className="absolute inset-0 bg-black/40"
            onClick={handleActivateCancel}
            aria-hidden="true"
          />
          <div className="relative z-10 bg-white rounded-[8px] p-6 shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-8 items-end justify-end min-w-[500px]">
            <div className="flex flex-col gap-4 items-start justify-center w-full">
              <div className="flex gap-2 items-start w-full">
                <h2 className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
                  계정을 활성화하시겠습니까?
                </h2>
              </div>
            </div>
            <div className="flex gap-2 items-center justify-end">
              <button
                type="button"
                onClick={handleActivateCancel}
                className="h-[40px] px-2 rounded-[8px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] w-[80px] cursor-pointer hover:bg-[#e5e7eb] transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleActivateConfirm}
                className="h-[40px] px-4 rounded-[8px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white cursor-pointer hover:bg-[#1a2478] transition-colors"
              >
                활성화하기
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 비활성화 확인 모달 */}
      {isDeactivateModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div 
            className="absolute inset-0 bg-black/40"
            onClick={handleDeactivateCancel}
            aria-hidden="true"
          />
          <div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end min-w-[500px]">
            <div className="flex flex-col gap-[16px] items-start justify-center w-full">
              <h2 className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
                계정을 비활성화 하시겠습니까?
              </h2>
              <p className="text-[15px] font-normal leading-[1.5] text-[#4c5561]">
                학습자가 강좌를 수강 중일 경우 강좌 수강이 어렵습니다.
                <br />
                계정을 비활성화 처리하시겠습니까?
              </p>
            </div>
            <div className="flex gap-2 items-center justify-end">
              <button
                type="button"
                onClick={handleDeactivateCancel}
                className="h-[40px] px-2 rounded-[8px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] w-[80px] cursor-pointer hover:bg-[#e5e7eb] transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleDeactivateConfirm}
                className="h-[40px] px-4 rounded-[8px] bg-red-50 text-[16px] font-semibold leading-[1.5] text-[#f64c4c] cursor-pointer hover:bg-red-100 transition-colors"
              >
                비활성화하기
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 활성화 완료 토스트 */}
      {showToast && (
        <div className="fixed right-[60px] bottom-[60px] z-50">
          <div className="bg-white border border-[#dee1e6] rounded-[8px] p-4 min-w-[360px] flex gap-[10px] items-center">
            <div className="relative shrink-0 w-[16.667px] h-[16.667px]">
              <svg width="17" height="17" viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="8.5" cy="8.5" r="8.5" fill="#384FBF"/>
                <path d="M5.5 8.5L7.5 10.5L11.5 6.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] text-nowrap">
              {toastMessage}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

