import type { Milestone, Task, TeamMember } from '../types';
import { isRoutineTask, isProjectTask } from './taskType';

/** 셀 컬럼 기본 순서 — 팀원 데이터에 다른 셀이 있으면 뒤에 추가 */
export const DEFAULT_CELL_ORDER = ['HR', '총무'] as const;

/** DB 저장값 → 화면 표시명 (저장값은 그대로, 라벨만 변경) */
const CELL_DISPLAY_LABELS: Record<string, string> = {
  HR: '인사',
};

export function getCellLabel(cell: string | null | undefined): string {
  if (!cell) return '';
  return CELL_DISPLAY_LABELS[cell] ?? cell;
}

const LEADER_CELLS = new Set(['', '리더', '팀장']);

export function isLeaderCell(cell: string | null | undefined): boolean {
  if (!cell || LEADER_CELLS.has(cell)) return true;
  return false;
}

const RANK_ORDER: Record<string, number> = {
  수석연구원: 1,
  책임연구원: 2,
  선임연구원: 3,
  연구원: 4,
};

const CELL_ORDER: Record<string, number> = {
  HR: 1,
  총무: 2,
};

export function compareTeamMembers(a: TeamMember, b: TeamMember): number {
  const aLeader = a.role?.includes('팀장') || isLeaderCell(a.cell);
  const bLeader = b.role?.includes('팀장') || isLeaderCell(b.cell);
  if (aLeader && !bLeader) return -1;
  if (!aLeader && bLeader) return 1;

  const aCell = CELL_ORDER[a.cell ?? ''] ?? 99;
  const bCell = CELL_ORDER[b.cell ?? ''] ?? 99;
  if (aCell !== bCell) return aCell - bCell;

  const aCellLead = a.role?.includes('셀장');
  const bCellLead = b.role?.includes('셀장');
  if (aCellLead && !bCellLead) return -1;
  if (!aCellLead && bCellLead) return 1;

  const aRank = RANK_ORDER[a.rank ?? ''] ?? 99;
  const bRank = RANK_ORDER[b.rank ?? ''] ?? 99;
  if (aRank !== bRank) return aRank - bRank;

  const aOrder = a.sortOrder ?? 0;
  const bOrder = b.sortOrder ?? 0;
  if (aOrder !== bOrder) return aOrder - bOrder;

  return a.name.localeCompare(b.name, 'ko');
}

export function groupTeamMembers(members: TeamMember[]) {
  const cellKeys: string[] = [...DEFAULT_CELL_ORDER];
  members.forEach((m) => {
    if (m.cell && !isLeaderCell(m.cell) && !cellKeys.includes(m.cell)) {
      cellKeys.push(m.cell);
    }
  });

  const groups: Record<string, TeamMember[]> = { 리더: [] };
  cellKeys.forEach((k) => { groups[k] = []; });

  members.forEach((m) => {
    if (isLeaderCell(m.cell) || m.role?.includes('팀장')) {
      groups.리더.push(m);
    } else if (m.cell && groups[m.cell]) {
      groups[m.cell].push(m);
    } else {
      groups.리더.push(m);
    }
  });

  Object.keys(groups).forEach((key) => {
    groups[key].sort(compareTeamMembers);
  });

  return { groups, cellKeys };
}

export function isTaskPm(memberId: string, task: Task): boolean {
  return task.pmMember?.id === memberId || task.pmMemberId === memberId;
}

export function isTaskAssignee(memberId: string, task: Task): boolean {
  return task.assigneeMembers?.some((a) => a.id === memberId) ?? false;
}

/** 해당 팀원이 이 업무에서 맡은 역할 */
export function getMemberTaskRole(
  memberId: string,
  task: Task,
): 'pm' | 'assignee' | 'both' | null {
  const pm = isTaskPm(memberId, task);
  const assignee = isTaskAssignee(memberId, task);
  if (pm && assignee) return 'both';
  if (pm) return 'pm';
  if (assignee) return 'assignee';
  return null;
}

export function getMemberTaskRoleLabel(role: ReturnType<typeof getMemberTaskRole>): string | null {
  if (role === 'both') return 'PM · 담당';
  if (role === 'pm') return 'PM';
  if (role === 'assignee') return '담당';
  return null;
}

export function getMemberTasks(
  memberId: string,
  tasks: Task[],
  scope: 'all' | 'project' | 'routine' = 'all',
): Task[] {
  return tasks.filter((t) => {
    if (t.status === 'DONE' || t.status === 'CANCELLED') return false;
    if (scope === 'project' && !isProjectTask(t.taskType)) return false;
    if (scope === 'routine' && !isRoutineTask(t.taskType)) return false;
    return isTaskPm(memberId, t) || isTaskAssignee(memberId, t);
  });
}

/** 상세 헤더 — PM / 담당 분리 (PM과 동일 인원은 담당에서 제외) */
export function getTaskPeopleHeaderParts(task: Task): {
  pmName: string | null;
  assigneeNames: string[];
} {
  const pmId = task.pmMember?.id ?? task.pmMemberId ?? null;
  const pmName = task.pmMember?.name?.trim() || null;
  const assigneeNames = (task.assigneeMembers ?? [])
    .filter((m) => m.name?.trim() && m.id !== pmId)
    .map((m) => m.name!.trim());

  return { pmName, assigneeNames };
}

/** 상세 헤더 — 단계(마일스톤) PM / 담당 */
export function getMilestonePeopleHeaderParts(milestone: Milestone | null | undefined): {
  pmName: string | null;
  assigneeNames: string[];
} {
  if (!milestone) return { pmName: null, assigneeNames: [] };
  const pmId = milestone.pmMember?.id ?? milestone.pmMemberId ?? null;
  const pmName = milestone.pmMember?.name?.trim() || null;
  const assigneeNames = (milestone.assigneeMembers ?? [])
    .filter((m) => m.name?.trim() && m.id !== pmId)
    .map((m) => m.name!.trim());
  return { pmName, assigneeNames };
}

export function getHighlightMemberIds(task: Task | null | undefined): string[] {
  if (!task) return [];
  const ids: string[] = [];
  const pmId = task.pmMember?.id ?? task.pmMemberId;
  if (pmId) ids.push(pmId);
  task.assigneeMembers?.forEach((m) => {
    if (m.id && !ids.includes(m.id)) ids.push(m.id);
  });
  return ids;
}

export function taskStatusBadge(task: Task): { label: string; variant: 'always' | 'hold' | 'wait' | 'progress' | 'done' } {
  if (task.taskType && isRoutineTask(task.taskType)) {
    return { label: '상시', variant: 'always' };
  }
  if (task.status === 'DONE') return { label: '완료', variant: 'done' };
  if (task.status === 'REVIEW') return { label: '홀딩', variant: 'hold' };
  if (task.status === 'TODO') return { label: '대기', variant: 'wait' };
  return { label: `${task.progress}%`, variant: 'progress' };
}

export function taskSubtitle(task: Task): string {
  const parts = [task.section, task.tag].filter(Boolean);
  return parts.length ? `| ${parts.join(' · ')}` : '';
}
