import { useRef, useState } from 'react';

import { formatBoardCalendarPill } from '../../lib/boardCalendar';
import { isDetailWindowOpen } from '../../lib/dualMonitor';

import {

  FILTER_ALL,

  isStatusChipActive,

  type CoreStatusFilter,

} from '../../lib/statusFilters';

import { BoardCalendarPopover } from './BoardCalendarPopover';
import { CalendarIcon, DualMonitorIcon, PlusIcon, UsersIcon } from './HeaderIcons';



interface Stats {

  total: number;

  inProgress: number;

  review: number;

  done: number;

  issues: number;

}



interface DashboardHeaderProps {

  quarter: string;

  referenceWeekMonday: Date;

  weekLensActive: boolean;

  onSelectWeek: (d: Date) => void;

  onSelectQuarter: (quarterKey: string) => void;

  onReturnToCurrentQuarter: () => void;

  stats: Stats;

  activeFilters: string[];

  issueFilterActive: boolean;

  onToggleAll: () => void;

  onToggleStatus: (key: CoreStatusFilter) => void;

  onToggleIssue: () => void;

  onOpenDetailWindow: () => void | Promise<void>;

  onOpenTaskManager: () => void;

  teamPanelOpen: boolean;

  onToggleTeamPanel: () => void;

}



const STAT_ACCENT = {

  전체: 'text-[#ffdb3a]',

  IN_PROGRESS: 'text-[#10b981]',

  REVIEW: 'text-[#ff9f0a]',

  DONE: 'text-[#b0b0b0]',

  ISSUES: 'text-[#ff5252]',

} as const;



type StatKey = keyof typeof STAT_ACCENT;



export function DashboardHeader({

  quarter,

  referenceWeekMonday,

  weekLensActive,

  onSelectWeek,

  onSelectQuarter,

  onReturnToCurrentQuarter,

  stats,

  activeFilters,

  issueFilterActive,

  onToggleAll,

  onToggleStatus,

  onToggleIssue,

  onOpenDetailWindow,

  onOpenTaskManager,

  teamPanelOpen,

  onToggleTeamPanel,

}: DashboardHeaderProps) {

  const [detailViewActive, setDetailViewActive] = useState(isDetailWindowOpen);
  const [calendarOpen, setCalendarOpen] = useState(false);
  const calendarBtnRef = useRef<HTMLButtonElement>(null);

  const quarterLabel = quarter.replace(/^(\d{4})-Q(\d)$/, '$1 $2분기 업무');



  const handleOpenDetailWindow = () => {

    void Promise.resolve(onOpenDetailWindow()).then(() => {

      setDetailViewActive(isDetailWindowOpen());

    });

  };



  const statItems: Array<{

    label: string;

    value: number;

    statusKey: StatKey;

    onClick: () => void;

    isActive: boolean;

  }> = [

    {

      label: '전체',

      value: stats.total,

      statusKey: '전체',

      onClick: onToggleAll,

      isActive: isStatusChipActive(FILTER_ALL, activeFilters, issueFilterActive),

    },

    {

      label: '진행',

      value: stats.inProgress,

      statusKey: 'IN_PROGRESS',

      onClick: () => onToggleStatus('IN_PROGRESS'),

      isActive: isStatusChipActive('IN_PROGRESS', activeFilters, issueFilterActive),

    },

    {

      label: '보류',

      value: stats.review,

      statusKey: 'REVIEW',

      onClick: () => onToggleStatus('REVIEW'),

      isActive: isStatusChipActive('REVIEW', activeFilters, issueFilterActive),

    },

    {

      label: '완료',

      value: stats.done,

      statusKey: 'DONE',

      onClick: () => onToggleStatus('DONE'),

      isActive: isStatusChipActive('DONE', activeFilters, issueFilterActive),

    },

    {

      label: '이슈',

      value: stats.issues,

      statusKey: 'ISSUES',

      onClick: onToggleIssue,

      isActive: issueFilterActive,

    },

  ];



  return (

    <header className="dashboard-header-bar shrink-0">

      <div className="side-left-group min-w-0 shrink-0">

        <span className="side-title-main main_tit flex shrink-0 items-center gap-[10px] text-[20px] font-bold tracking-[-0.5px] text-[#bad8ca]">

          <span>총괄기획실</span>

          <span>|</span>

          <span>People Growth Hub</span>

        </span>

        <button
          type="button"
          title="팀 현황"
          className={`team-status-btn-new ${teamPanelOpen ? 'active' : ''}`}
          onClick={onToggleTeamPanel}
        >
          <UsersIcon size={16} />
        </button>

        <button type="button" onClick={onOpenTaskManager} title="신규 프로젝트 추가" className="header-action-btn-new">
          <PlusIcon size={16} />
        </button>

        <button
          type="button"
          onClick={handleOpenDetailWindow}
          title="듀얼뷰"
          className={`header-view-btn-new ${detailViewActive ? 'active' : ''}`}
        >
          <DualMonitorIcon size={16} />
        </button>

      </div>

      <div className="header-stats-bar side-polygon-stats">

        <div className="poly-stat-item" style={{ fontSize: '18px', gap: '8px' }}>

          <span className="poly-stat-quarter header-stat-text">{quarterLabel}</span>

          <span className="poly-stat-bullet header-stat-text">·</span>

          {statItems.map((item, index) => (

            <span key={item.statusKey} className="contents">

              {(index === 1 || index === 4) && <StatDivider />}

              <StatClick

                label={item.label}

                value={item.value}

                accent={STAT_ACCENT[item.statusKey]}

                isActive={item.isActive}

                onClick={item.onClick}

              />

            </span>

          ))}

        </div>

      </div>



      <div className="side-right-actions shrink-0">
        <div className="header-calendar-slot">
          <span className="board-calendar-ref-text">
            {formatBoardCalendarPill(quarter, weekLensActive, referenceWeekMonday)}
          </span>
          <button
            ref={calendarBtnRef}
            type="button"
            className={`header-calendar-btn-new${calendarOpen ? ' active' : ''}`}
            title="주차 · 분기 선택"
            aria-expanded={calendarOpen}
            aria-label="캘린더 열기"
            onClick={() => setCalendarOpen((open) => !open)}
          >
            <CalendarIcon size={16} />
          </button>
          {calendarOpen && (
            <BoardCalendarPopover
              selectedQuarter={quarter}
              referenceWeekMonday={referenceWeekMonday}
              weekLensActive={weekLensActive}
              onSelectWeek={onSelectWeek}
              onSelectQuarter={onSelectQuarter}
              onReturnToCurrentQuarter={onReturnToCurrentQuarter}
              onClose={() => setCalendarOpen(false)}
              anchorRef={calendarBtnRef}
            />
          )}
        </div>
      </div>

    </header>

  );

}



function StatDivider() {

  return <div className="poly-stat-divider" aria-hidden />;

}



interface StatClickProps {

  label: string;

  value: number;

  accent: string;

  isActive: boolean;

  onClick: () => void;

}



function StatClick({ label, value, accent, isActive, onClick }: StatClickProps) {

  return (

    <span

      role="button"

      tabIndex={0}

      onClick={onClick}

      onKeyDown={(e) => {

        if (e.key === 'Enter' || e.key === ' ') {

          e.preventDefault();

          onClick();

        }

      }}

      className={`poly-click-stat header-stat-text ${isActive ? 'active' : ''}`}

      style={{ cursor: 'pointer', padding: '2px 6px', borderRadius: '4px' }}

    >

      {label}{' '}

      <span className={`poly-stat-val ${accent}`}>{value}</span>

      <span className="poly-stat-unit"> 건</span>

    </span>

  );

}


