'use client';

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

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[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  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 [deactivateReason, setDeactivateReason] = useState('');
  const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  const ITEMS_PER_PAGE = 10;

  // API에서 사용자 데이터 가져오기
  useEffect(() => {
    async function fetchUsers() {
      try {
        setIsLoading(true);
        setError(null);
        
        // 외부 API 호출
        const response = await apiService.getUsersCompact();
        const data = response.data;
        
        // API 응답이 배열이 아닌 경우 처리 (예: { items: [...] } 형태)
        let usersArray: any[] = [];
        if (Array.isArray(data)) {
          usersArray = data;
        } else if (data && typeof data === 'object') {
          usersArray = data.items || data.users || data.data || data.list || [];
        }
        
        // API 응답 데이터를 UserRow 형식으로 변환
        const transformedUsers: UserRow[] = usersArray.length > 0
          ? usersArray.map((user: any) => {
              // 가입일을 YYYY-MM-DD 형식으로 변환
              const formatDate = (dateString: string | null | undefined): string => {
                if (!dateString) return new Date().toISOString().split('T')[0];
                try {
                  const date = new Date(dateString);
                  return date.toISOString().split('T')[0];
                } catch {
                  return new Date().toISOString().split('T')[0];
                }
              };
              
              // null 값을 명시적으로 처리
              const getValue = (value: any, fallback: string = '-') => {
                if (value === null || value === undefined) return fallback;
                if (typeof value === 'string' && value.trim() === '') return fallback;
                return String(value);
              };
              
              // status가 "ACTIVE"이면 활성화, 아니면 비활성화
              const accountStatus: AccountStatus = 
                user.status === 'ACTIVE' || user.status === 'active' ? 'active' : 'inactive';
              
              // role 데이터 처리 (API에서 role이 없을 수 있음)
              let userRole: RoleType = 'learner'; // 기본값
              if (user.role) {
                const roleLower = String(user.role).toLowerCase();
                if (roleLower === 'instructor' || roleLower === '강사') {
                  userRole = 'instructor';
                } else if (roleLower === 'admin' || roleLower === '관리자') {
                  userRole = 'admin';
                } else {
                  userRole = 'learner';
                }
              }
              
              return {
                id: String(user.id || user.userId || Math.random()),
                joinDate: formatDate(user.createdAt || user.joinDate || user.join_date),
                name: getValue(user.name || user.userName, '-'),
                email: getValue(user.email || user.userEmail, '-'),
                role: userRole,
                status: accountStatus,
              };
            })
          : [];
        
        setUsers(transformedUsers);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '사용자 데이터를 불러오는 중 오류가 발생했습니다.';
        setError(errorMessage);
        console.error('사용자 데이터 로드 오류:', err);
      } finally {
        setIsLoading(false);
      }
    }

    fetchUsers();
  }, [currentPage]);

  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);
  }

  async function handleActivateConfirm() {
    if (!selectedUserId) {
      setIsActivateModalOpen(false);
      setSelectedUserId(null);
      return;
    }

    try {
      // selectedUserId로 사용자 찾기
      const user = users.find(u => u.id === selectedUserId);
      if (!user || !user.email || user.email === '-') {
        setToastMessage('사용자 정보를 찾을 수 없습니다.');
        setShowToast(true);
        setTimeout(() => {
          setShowToast(false);
        }, 3000);
        setIsActivateModalOpen(false);
        setSelectedUserId(null);
        return;
      }

      await apiService.unsuspendUser(selectedUserId);

      // API 호출 성공 시 로컬 상태 업데이트
      setUsers(prevUsers => 
        prevUsers.map(u => 
          u.id === selectedUserId 
            ? { ...u, status: 'active' }
            : u
        )
      );
      setToastMessage('계정을 활성화했습니다.');
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '계정 활성화 중 오류가 발생했습니다.';
      setToastMessage(errorMessage);
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
      console.error('계정 활성화 오류:', err);
    } finally {
      setIsActivateModalOpen(false);
      setSelectedUserId(null);
    }
  }

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

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

  async function handleDeactivateConfirm() {
    if (!selectedUserId) {
      setIsDeactivateModalOpen(false);
      setSelectedUserId(null);
      setDeactivateReason('');
      return;
    }

    try {
      await apiService.suspendUser(selectedUserId);

      // API 호출 성공 시 로컬 상태 업데이트
      setUsers(prevUsers => 
        prevUsers.map(user => 
          user.id === selectedUserId 
            ? { ...user, status: 'inactive' }
            : user
        )
      );
      setToastMessage('계정을 비활성화했습니다.');
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '계정 비활성화 중 오류가 발생했습니다.';
      setToastMessage(errorMessage);
      setShowToast(true);
      setTimeout(() => {
        setShowToast(false);
      }, 3000);
      console.error('계정 비활성화 오류:', err);
    } finally {
      setIsDeactivateModalOpen(false);
      setSelectedUserId(null);
      setDeactivateReason('');
    }
  }

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

  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-normal text-text-title">
                권한 설정
              </h1>
            </div>
            {/* 탭 네비게이션 */}
            {/* <div>
              <div className="flex items-center gap-8 border-b border-input-border">
                {[
                  { 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-normal transition-colors relative cursor-pointer",
                      activeTab === tab.id
                        ? "text-active-button font-semibold"
                        : "text-text-label",
                    ].join(" ")}
                  >
                    {tab.label}
                    {activeTab === tab.id && (
                      <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-active-button" />
                    )}
                  </button>
                ))}
              </div>
            </div> */}

            {/* 콘텐츠 영역 */}
            <div className="flex-1 pt-8 flex flex-col">
              {isLoading ? (
                <div className="rounded-lg border border-input-border bg-white min-h-[400px] flex items-center justify-center">
                  <p className="text-[16px] font-medium leading-normal text-neutral-700">
                    데이터를 불러오는 중...
                  </p>
                </div>
              ) : error ? (
                <div className="rounded-lg border border-input-border bg-white min-h-[400px] flex items-center justify-center">
                  <p className="text-[16px] font-medium leading-normal text-error">
                    {error}
                  </p>
                </div>
              ) : filteredUsers.length === 0 ? (
                <div className="rounded-lg border border-input-border bg-white min-h-[400px] flex items-center justify-center">
                  <p className="text-[16px] font-medium leading-normal text-neutral-700">
                    현재 관리할 수 있는 회원 계정이 없습니다.
                  </p>
                </div>
              ) : (
                <>
                  <div className="rounded-[8px]">
                    <div className="w-full rounded-[8px] border border-input-border overflow-visible">
                      <table className="min-w-full border-collapse">
                        <colgroup>
                          <col style={{ width: 200 }} />
                          <col />
                          <col />
                          <col style={{ width: 150 }} />
                          <col style={{ width: 150 }} />
                        </colgroup>
                        <thead>
                          <tr className="h-12 bg-gray-50 text-left">
                            <th className="border-r border-input-border px-4 text-[14px] font-semibold leading-normal text-basic-text">가입일</th>
                            <th className="border-r border-input-border px-4 text-[14px] font-semibold leading-normal text-basic-text">성명</th>
                            <th className="border-r border-input-border px-4 text-[14px] font-semibold leading-normal text-basic-text">아이디(이메일)</th>
                            <th className="border-r border-input-border px-4 text-[14px] font-semibold leading-normal text-basic-text">계정상태</th>
                            <th className="px-4 text-center text-[14px] font-semibold leading-normal text-basic-text">계정관리</th>
                          </tr>
                        </thead>
                        <tbody>
                          {paginatedUsers.map((user) => (
                          <tr
                            key={user.id}
                            className="h-12"
                          >
                            <td className="border-t border-r border-input-border px-4 text-[13px] leading-normal text-text-body whitespace-nowrap">
                              {user.joinDate}
                            </td>
                            <td className="border-t border-r border-input-border px-4 text-[13px] leading-normal text-text-body whitespace-nowrap">
                              {user.name}
                            </td>
                            <td className="border-t border-r border-input-border px-4 text-[13px] leading-normal text-text-body whitespace-nowrap">
                              {user.email}
                            </td>
                            <td className="border-t border-r border-input-border px-4 text-[13px] leading-normal text-text-body whitespace-nowrap">
                              {user.status === 'active' ? (
                                <div className="inline-flex items-center justify-center h-[20px] px-[4px] rounded-[4px] bg-bg-primary-light">
                                  <span className="text-[13px] font-semibold leading-[1.4] text-primary whitespace-nowrap">
                                    {statusLabels[user.status]}
                                  </span>
                                </div>
                              ) : (
                                <div className="inline-flex items-center justify-center h-[20px] px-[4px] rounded-[4px] bg-bg-gray-light">
                                  <span className="text-[13px] font-semibold leading-[1.4] text-basic-text whitespace-nowrap">
                                    {statusLabels[user.status]}
                                  </span>
                                </div>
                              )}
                            </td>
                            <td className="border-t border-input-border px-4 text-center text-[13px] leading-normal text-text-body 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-neutral-700 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-neutral-700 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-bg-primary-light' : 'bg-white',
                              ].join(' ')}
                            >
                              <span className="text-[16px] leading-[1.4] text-neutral-700">{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-neutral-700 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-neutral-700 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-normal text-neutral-700">
                  계정을 활성화하시겠습니까?
                </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-bg-gray-light text-[16px] font-semibold leading-normal text-basic-text w-[80px] cursor-pointer hover:bg-bg-gray-hover transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleActivateConfirm}
                className="h-[40px] px-4 rounded-[8px] bg-active-button text-[16px] font-semibold leading-normal text-white cursor-pointer hover:bg-active-button-hover 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-normal text-[#333c47]">
                계정을 비활성화 하시겠습니까?
              </h2>
              <p className="text-[15px] font-normal leading-normal text-basic-text">
                학습자가 강좌를 수강 중일 경우 강좌 수강이 어렵습니다.
                <br />
                계정을 비활성화 처리하시겠습니까?
              </p>
              <div className="w-full">
                <input
                  type="text"
                  value={deactivateReason}
                  onChange={(e) => setDeactivateReason(e.target.value)}
                  placeholder="비활성화 사유를 입력해주세요"
                  className="w-full h-[40px] px-[12px] rounded-[8px] border border-input-border text-[14px] leading-normal text-text-body placeholder:text-text-placeholder focus:outline-none focus:ring-2 focus:ring-active-button focus:border-transparent"
                />
              </div>
            </div>
            <div className="flex gap-2 items-center justify-end">
              <button
                type="button"
                onClick={handleDeactivateCancel}
                className="h-[40px] px-2 rounded-[8px] bg-bg-gray-light text-[16px] font-semibold leading-normal text-basic-text w-[80px] cursor-pointer hover:bg-bg-gray-hover transition-colors"
              >
                취소
              </button>
              <button
                type="button"
                onClick={handleDeactivateConfirm}
                className="h-[40px] px-4 rounded-[8px] bg-red-50 text-[16px] font-semibold leading-normal text-error 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-input-border 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="var(--color-primary)"/>
                <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-normal text-text-body text-nowrap">
              {toastMessage}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

