import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { TeamMemberFormModal } from '../components/admin/TeamMemberFormModal';
import { TeamMemberAvatar } from '../components/dashboard/TeamMemberAvatar';
import {
  EMPTY_MEMBER_FORM,
  memberToForm,
  useTeamMembersAdmin,
  type TeamMemberForm,
} from '../hooks/useTeamMembersAdmin';
import { getCellLabel, groupTeamMembers, isLeaderCell } from '../lib/teamStatus';
import type { TeamMember } from '../types';

export default function AdminPage() {
  const { query, create, update, remove, getApiErrorMessage } = useTeamMembersAdmin();
  const members = query.data ?? [];

  const [modalMode, setModalMode] = useState<'add' | 'edit' | null>(null);
  const [editingMember, setEditingMember] = useState<TeamMember | null>(null);
  const [defaultCell, setDefaultCell] = useState('HR');

  const { groups, cellKeys } = useMemo(() => groupTeamMembers(members), [members]);

  const sections = useMemo(() => {
    const list: { key: string; label: string; members: TeamMember[] }[] = [];
    if ((groups.리더?.length ?? 0) > 0) {
      list.push({ key: '리더', label: '팀장', members: groups.리더 });
    }
    cellKeys.forEach((key) => {
      const cellMembers = groups[key] ?? [];
      if (cellMembers.length > 0) {
        list.push({ key, label: getCellLabel(key), members: cellMembers });
      }
    });
    return list;
  }, [groups, cellKeys]);

  const openAdd = (cell = 'HR') => {
    setEditingMember(null);
    setDefaultCell(cell);
    setModalMode('add');
  };

  const openEdit = (member: TeamMember) => {
    setEditingMember(member);
    setModalMode('edit');
  };

  const closeModal = () => {
    setModalMode(null);
    setEditingMember(null);
  };

  const handleSave = async (form: TeamMemberForm) => {
    try {
      if (modalMode === 'add') {
        await create.mutateAsync(form);
      } else if (editingMember) {
        await update.mutateAsync({ id: editingMember.id, form });
      }
      closeModal();
    } catch (err) {
      alert(getApiErrorMessage(err, '저장에 실패했습니다.'));
    }
  };

  const handleDelete = async (member: TeamMember) => {
    if (!window.confirm(`"${member.name}" 팀원을 삭제(비활성)하시겠습니까?`)) return;
    try {
      await remove.mutateAsync(member.id);
    } catch (err) {
      alert(getApiErrorMessage(err, '삭제에 실패했습니다.'));
    }
  };

  const saving = create.isPending || update.isPending;

  return (
    <div className="admin-page">
      <header className="admin-header">
        <div className="admin-header-left">
          <Link to="/" className="admin-back-link">← 대시보드</Link>
          <div className="admin-header-title">
            <span className="admin-header-org">총괄기획실</span>
            <span className="admin-header-sep">|</span>
            <span>팀원 관리</span>
          </div>
        </div>
        <div className="admin-header-actions">
          <button type="button" className="admin-btn-primary" onClick={() => openAdd('리더')}>
            + 팀원 추가
          </button>
        </div>
      </header>

      <div className="admin-toolbar">
        <div className="admin-stat-chips">
          <span className="admin-stat-chip admin-stat-total">
            전체 <strong>{members.length}</strong>명
          </span>
          <span className="admin-stat-chip">
            팀장 <strong>{groups.리더?.length ?? 0}</strong>명
          </span>
          <span className="admin-stat-chip">
            인사 <strong>{groups.HR?.length ?? 0}</strong>명
          </span>
          <span className="admin-stat-chip">
            총무 <strong>{groups.총무?.length ?? 0}</strong>명
          </span>
        </div>
        <p className="admin-toolbar-hint">
          등록한 팀원은 대시보드 <strong>팀 인원 현황</strong>에 표시됩니다. 업무 PM·담당자 선택에도 사용됩니다.
        </p>
      </div>

      <main className="admin-main">
        {query.isLoading && (
          <div className="admin-empty">데이터를 불러오는 중…</div>
        )}

        {!query.isLoading && members.length === 0 && (
          <div className="admin-empty-card">
            <h3>등록된 팀원이 없습니다</h3>
            <p>팀장 1명, 인사 2명, 총무 2명 순으로 추가해 보세요.</p>
            <div className="admin-quick-add">
              <button type="button" className="admin-btn-outline" onClick={() => openAdd('리더')}>
                + 팀장 추가
              </button>
              <button type="button" className="admin-btn-outline" onClick={() => openAdd('HR')}>
                + 인사 추가
              </button>
              <button type="button" className="admin-btn-outline" onClick={() => openAdd('총무')}>
                + 총무 추가
              </button>
            </div>
          </div>
        )}

        {sections.map((section) => (
          <section key={section.key} className="admin-section">
            <div className="admin-section-head">
              <div className="admin-section-title">
                <span>{section.label}</span>
                <span className="admin-section-badge">{section.members.length}명</span>
              </div>
              <button
                type="button"
                className="admin-btn-outline admin-btn-sm"
                onClick={() => openAdd(isLeaderCell(section.key) ? '리더' : section.key)}
              >
                + {section.label} 추가
              </button>
            </div>

            <div className="admin-member-table-wrap">
              <table className="admin-member-table">
                <thead>
                  <tr>
                    <th className="w-avatar" />
                    <th>이름</th>
                    <th>직급 · 직책</th>
                    <th>연락처</th>
                    <th>순서</th>
                    <th className="w-actions" />
                  </tr>
                </thead>
                <tbody>
                  {section.members.map((member) => (
                    <tr key={member.id}>
                      <td>
                        <TeamMemberAvatar member={member} size="member" />
                      </td>
                      <td>
                        <span className="admin-member-name">{member.name}</span>
                        <span className="admin-member-cell-tag">{getCellLabel(member.cell) || '팀장'}</span>
                      </td>
                      <td>
                        {[member.rank, member.role].filter(Boolean).join(' · ') || '—'}
                      </td>
                      <td className="admin-contact">{member.contact ?? '—'}</td>
                      <td className="admin-sort">{member.sortOrder ?? 0}</td>
                      <td>
                        <div className="admin-row-actions">
                          <button
                            type="button"
                            className="admin-icon-btn"
                            title="수정"
                            onClick={() => openEdit(member)}
                          >
                            ✏
                          </button>
                          <button
                            type="button"
                            className="admin-icon-btn admin-icon-btn-danger"
                            title="삭제"
                            onClick={() => handleDelete(member)}
                          >
                            🗑
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ))}

        {members.length > 0 && (
          <div className="admin-footer-note">
            <Link to="/" className="admin-preview-link">
              대시보드에서 팀 인원 현황 미리보기 →
            </Link>
          </div>
        )}
      </main>

      {modalMode && (
        <TeamMemberFormModal
          mode={modalMode}
          initial={
            modalMode === 'edit' && editingMember
              ? memberToForm(editingMember)
              : { ...EMPTY_MEMBER_FORM, cell: defaultCell }
          }
          onSave={handleSave}
          onClose={closeModal}
          saving={saving}
        />
      )}
    </div>
  );
}
