import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import type { Task, TeamMember } from '../../types';
import {
  getCellLabel,
  getHighlightMemberIds,
  groupTeamMembers,
} from '../../lib/teamStatus';
import { TeamMemberAvatar } from './TeamMemberAvatar';
import { MemberTaskTooltip } from './MemberTaskTooltip';
import { UsersIcon } from './HeaderIcons';

function LayersIcon({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />
      <path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />
      <path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />
    </svg>
  );
}

function CloseIcon({ size = 20 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M18 6 6 18" />
      <path d="m6 6 12 12" />
    </svg>
  );
}

interface TeamStatusPanelProps {
  members: TeamMember[];
  tasks: Task[];
  showAllTasks: boolean;
  activeProjectId: string | null;
  onToggleShowAll: () => void;
  onProjectClick: (taskId: string | null) => void;
  onClose: () => void;
}

function MemberInfo({
  member,
  showAllTasks,
  isLeader,
}: {
  member: TeamMember;
  showAllTasks: boolean;
  isLeader: boolean;
}) {
  if (showAllTasks) {
    return (
      <>
        <span className="member-name">{member.name}</span>
        {member.rank && <span className="member-rank">{member.rank}</span>}
        {member.role && <span className="member-role">{member.role}</span>}
        {member.contact && <span className="member-contact">{member.contact}</span>}
      </>
    );
  }

  if (isLeader) {
    return (
      <>
        <div className="leader-name-row">
          <span className="leader-name">{member.name}</span>
          <span className="leader-sub">
            {[member.rank, member.role].filter(Boolean).join(' · ')}
          </span>
        </div>
        {member.contact && <span className="member-contact">{member.contact}</span>}
      </>
    );
  }

  return (
    <>
      <div className="member-name-row">
        <span className="member-name">{member.name}</span>
        <span className="member-role">
          {[member.rank, member.role].filter(Boolean).join(' · ')}
        </span>
      </div>
      {member.contact && <span className="member-contact">{member.contact}</span>}
    </>
  );
}

export function TeamStatusPanel({
  members,
  tasks,
  showAllTasks,
  activeProjectId,
  onToggleShowAll,
  onProjectClick,
  onClose,
}: TeamStatusPanelProps) {
  const activeTask = activeProjectId ? tasks.find((t) => t.id === activeProjectId) : null;
  const highlightIds = useMemo(() => getHighlightMemberIds(activeTask), [activeTask]);

  const { groups, cellKeys } = useMemo(() => groupTeamMembers(members), [members]);
  const visibleCells = cellKeys.filter((key) => (groups[key]?.length ?? 0) > 0);
  const leaders = groups.리더 ?? [];

  if (members.length === 0) {
    return (
      <div className="team-overlay">
        <div className="team-panel-header">
          <div className="team-panel-title">
            <UsersIcon size={20} />
            <span>팀 인원 현황</span>
            <span className="team-total-badge">0명</span>
          </div>
          <button type="button" className="team-close-btn" onClick={onClose} aria-label="닫기">
            <CloseIcon />
          </button>
        </div>
        <div className="team-tree-scroll team-empty-state">
          <p>등록된 팀원이 없습니다.</p>
          <p className="team-empty-hint">
            <Link to="/admin" className="admin-team-manage-link">팀원 관리</Link>
            에서 등록할 수 있습니다.
          </p>
        </div>
      </div>
    );
  }

  const renderMemberCard = (member: TeamMember, isLeader: boolean) => {
    const highlighted = highlightIds.includes(member.id);
    const cardClass = isLeader ? 'tree-leader-card' : 'tree-member-card';

    return (
      <div
        key={member.id}
        className={`${cardClass} ${highlighted ? 'highlighted-member' : ''}`}
        onClick={(e) => e.stopPropagation()}
      >
        <TeamMemberAvatar member={member} size={isLeader ? 'leader' : 'member'} />
        <div className={isLeader ? 'leader-info' : 'member-info-wrap'}>
          <MemberInfo member={member} showAllTasks={showAllTasks} isLeader={isLeader} />
        </div>
        <MemberTaskTooltip
          memberId={member.id}
          tasks={tasks}
          isStatic={showAllTasks}
          activeProjectId={activeProjectId}
          onProjectClick={onProjectClick}
        />
      </div>
    );
  };

  return (
    <div className="team-overlay">
      <div className="team-panel-header">
        <div className="team-panel-title">
          <UsersIcon size={20} />
          <span>팀 인원 현황</span>
          <span className="team-total-badge">{members.length}명</span>
        </div>
        <div className="team-panel-actions">
          <button
            type="button"
            className={`team-view-toggle ${showAllTasks ? 'active' : ''}`}
            onClick={onToggleShowAll}
          >
            <LayersIcon size={14} />
            <span>업무 전체보기</span>
          </button>
          <button type="button" className="team-close-btn" onClick={onClose} aria-label="닫기">
            <CloseIcon />
          </button>
        </div>
      </div>

      <div
        className={`team-tree-scroll ${showAllTasks ? 'show-all-tooltips' : ''}`}
        onClick={() => onProjectClick(null)}
      >
        {leaders.length > 0 && (
          <>
            <div className="tree-leaders-row">
              {leaders.map((m) => renderMemberCard(m, true))}
            </div>
            {visibleCells.length > 0 && <div className="tree-root-vline" />}
          </>
        )}

        {visibleCells.length > 0 && (
          <div className="tree-cells-row">
            {visibleCells.map((cellKey, index, arr) => {
              const cellMembers = groups[cellKey] ?? [];
              return (
                <div
                  key={cellKey}
                  className={`tree-cell-col ${index === arr.length - 1 ? 'last' : ''}`}
                >
                  <div className="tree-cell-hline-wrap" aria-hidden />
                  <div className="tree-cell-card static">
                    <span className="tree-cell-name">{getCellLabel(cellKey)}</span>
                    <span className="tree-badge">{cellMembers.length}명</span>
                  </div>
                  <div className="tree-members-list">
                    {cellMembers.map((m) => renderMemberCard(m, false))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
