import type { Task, TaskIssueEntry } from '../types';
import { normalizeTaskType } from './taskType';
import { parseIssueEntries } from './taskIssues';
import { getRoutineCategory } from './routineCategories';

export interface TaskFormData {
  title: string;
  section: string;
  category: string;
  tag: string;
  taskType: string;
  status: string;
  progress: number;
  description: string;
  detailDescription: string;
  issueEntries: TaskIssueEntry[];
  quarter: string;
  startDate: string;
  dueDate: string;
  pmMemberId: string;
  assigneeMemberIds: string[];
}

export const STATUS_OPTIONS = [
  { value: 'TODO', label: '대기' },
  { value: 'IN_PROGRESS', label: '진행' },
  { value: 'REVIEW', label: '보류' },
  { value: 'DONE', label: '완료' },
] as const;

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

function toDateInput(iso: string | null | undefined): string {
  if (!iso) return '';
  return new Date(iso).toISOString().slice(0, 10);
}

export function buildTaskFormState(opts: {
  task?: Task;
  variant: 'project' | 'routine';
  defaultSection?: string;
  defaultCategory?: string;
  defaultQuarter?: string;
}): TaskFormData {
  const { task, variant, defaultSection = '인사관리', defaultCategory = '채용 운영', defaultQuarter = '2026-Q2' } =
    opts;
  const isRoutine = variant === 'routine';

  return {
    title: task?.title ?? '',
    section: task?.section ?? defaultSection,
    category: (task ? getRoutineCategory(task) : null) ?? defaultCategory,
    tag: task?.tag ?? '',
    taskType: isRoutine ? '기반업무' : task?.taskType ? normalizeTaskType(task.taskType) : '실행과제',
    status: task?.status ?? 'TODO',
    progress: task?.progress ?? 0,
    description: task?.description ?? '',
    detailDescription: task?.detailDescription ?? '',
    issueEntries: task ? parseIssueEntries(task) : [],
    quarter: task?.quarter ?? defaultQuarter,
    startDate: toDateInput(task?.startDate),
    dueDate: toDateInput(task?.dueDate),
    pmMemberId: task?.pmMember?.id ?? task?.pmMemberId ?? '',
    assigneeMemberIds: task?.assigneeMembers?.map((m) => m.id) ?? [],
  };
}
