import type { Task } from '../../types';

const TAG_CONFIG: Record<string, { bg: string; text: string }> = {
  Growth:      { bg: 'bg-blue-100',    text: 'text-blue-800'    },
  Policy:      { bg: 'bg-purple-100',  text: 'text-purple-800'  },
  Performance: { bg: 'bg-emerald-100', text: 'text-emerald-800' },
  Culture:     { bg: 'bg-amber-100',   text: 'text-amber-800'   },
  Asset:       { bg: 'bg-cyan-100',    text: 'text-cyan-800'    },
  Space:       { bg: 'bg-indigo-100',  text: 'text-indigo-800'  },
  Safety:      { bg: 'bg-red-100',     text: 'text-red-800'     },
  Environment: { bg: 'bg-lime-100',    text: 'text-lime-800'    },
};

const STATUS_STYLE: Record<string, string> = {
  IN_PROGRESS: 'bg-blue-500 text-white',
  REVIEW:      'bg-orange-400 text-white',
  TODO:        'bg-gray-300 text-gray-700',
  DONE:        'bg-emerald-500 text-white',
  CANCELLED:   'bg-gray-200 text-gray-500',
};

const STATUS_LABEL: Record<string, string> = {
  IN_PROGRESS: '진행',
  REVIEW:      '보류',
  TODO:        '대기',
  DONE:        '완료',
  CANCELLED:   '취소',
};

function fmtDate(iso: string | null | undefined): string {
  if (!iso) return '';
  const d = new Date(iso);
  return `${d.getFullYear()}.${String(d.getMonth() + 1).padStart(2, '0')}.${String(d.getDate()).padStart(2, '0')}`;
}

interface Props {
  task: Task | null;
  onClose: () => void;
}

export function TaskDetailPanel({ task, onClose }: Props) {
  const isOpen = !!task;

  return (
    <div
      className={`h-full flex flex-col bg-white border-l border-gray-200 shadow-xl transition-all duration-300 ease-out overflow-hidden ${
        isOpen ? 'w-[420px]' : 'w-0'
      }`}
    >
      {task && (
        <>
          {/* 헤더 */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 shrink-0">
            <div className="flex items-center gap-2 min-w-0">
              <span className={`shrink-0 text-sm font-black px-2.5 py-0.5 rounded-full ${TAG_CONFIG[task.tag ?? '']?.bg ?? 'bg-gray-100'} ${TAG_CONFIG[task.tag ?? '']?.text ?? 'text-gray-600'}`}>
                {task.tag}
              </span>
              <span className={`shrink-0 text-sm font-bold px-2.5 py-0.5 rounded-full ${STATUS_STYLE[task.status]}`}>
                {STATUS_LABEL[task.status]}
              </span>
            </div>
            <button
              onClick={onClose}
              className="shrink-0 ml-2 text-gray-400 hover:text-gray-600 text-xl leading-none transition-colors"
            >
              ✕
            </button>
          </div>

          {/* 본문 */}
          <div className="flex-1 overflow-y-auto px-6 py-5 space-y-5">
            {/* 제목 */}
            <div>
              <p className="text-xs font-bold text-gray-400 mb-1">제목</p>
              <h2 className="text-2xl font-black text-gray-900 leading-snug">{task.title}</h2>
            </div>

            {/* 진행률 */}
            <div>
              <p className="text-xs font-bold text-gray-400 mb-1.5">진행률</p>
              <div className="flex items-center gap-3">
                <div className="flex-1 h-3 bg-gray-100 rounded-full overflow-hidden">
                  <div
                    className={`h-3 rounded-full transition-all ${
                      task.progress >= 70 ? 'bg-emerald-500' :
                      task.progress >= 40 ? 'bg-blue-400' :
                      'bg-orange-400'
                    }`}
                    style={{ width: `${task.progress}%` }}
                  />
                </div>
                <span className={`text-xl font-black min-w-[3rem] text-right ${
                  task.progress >= 70 ? 'text-emerald-500' :
                  task.progress >= 40 ? 'text-blue-400' :
                  'text-orange-400'
                }`}>
                  {task.progress}%
                </span>
              </div>
            </div>

            {/* 기간 */}
            {(task.startDate || task.dueDate) && (
              <div>
                <p className="text-xs font-bold text-gray-400 mb-1">기간</p>
                <p className="text-base font-medium text-gray-700">
                  {fmtDate(task.startDate)} ~ {fmtDate(task.dueDate)}
                </p>
              </div>
            )}

            {/* 섹션 / 업무유형 */}
            <div className="flex gap-6">
              {task.section && (
                <div>
                  <p className="text-xs font-bold text-gray-400 mb-1">부문</p>
                  <p className="text-base font-semibold text-gray-700">{task.section}</p>
                </div>
              )}
              {task.taskType && (
                <div>
                  <p className="text-xs font-bold text-gray-400 mb-1">유형</p>
                  <p className="text-base font-semibold text-gray-700">{task.taskType}</p>
                </div>
              )}
            </div>

            {/* 내용 */}
            {task.description && (
              <div>
                <p className="text-xs font-bold text-gray-400 mb-2">내용</p>
                <ul className="space-y-2">
                  {task.description.split('\n').filter(Boolean).map((b, i) => (
                    <li key={i} className="flex gap-2 text-base text-gray-700">
                      <span className="shrink-0 text-gray-300 mt-0.5">•</span>
                      <span>{b.replace(/^[•·\-]\s*/, '')}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* 이슈 메모 */}
            {task.issueNote && (
              <div className="rounded-xl bg-red-50 border border-red-100 px-4 py-3">
                <p className="text-xs font-bold text-red-400 mb-1">▶ 이슈</p>
                <p className="text-base font-semibold text-red-600">{task.issueNote}</p>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
