import { useState } from 'react';
import { createPortal } from 'react-dom';
import type { Task, TeamMember } from '../../types';
import { TaskFormFields } from './TaskFormFields';
import { buildTaskFormState, type TaskFormData } from '../../lib/taskFormState';

export type { TaskFormData };

interface TaskModalProps {
  mode: 'add' | 'edit';
  variant?: 'project' | 'routine';
  task?: Task;
  defaultSection?: string;
  defaultCategory?: string;
  defaultQuarter?: string;
  sectionOptions?: { value: string; label: string }[];
  teamMembers?: TeamMember[];
  onSave: (data: TaskFormData) => void;
  onClose: () => void;
}

export function TaskModal({
  mode,
  variant = 'project',
  task,
  defaultSection = '인사관리',
  defaultCategory = '채용 운영',
  defaultQuarter = '2026-Q2',
  sectionOptions,
  teamMembers = [],
  onSave,
  onClose,
}: TaskModalProps) {
  const isRoutine = variant === 'routine';
  const [form, setForm] = useState<TaskFormData>(() =>
    buildTaskFormState({ task, variant, defaultSection, defaultCategory, defaultQuarter }),
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      ...form,
      taskType: isRoutine ? '기반업무' : '실행과제',
    });
  };

  return createPortal(
    <div className="task-modal-overlay" onClick={onClose}>
      <div className="task-modal-shell" onClick={(e) => e.stopPropagation()}>
        <div className="task-modal-head">
          <h2 className="task-modal-title">
            {isRoutine
              ? mode === 'add'
                ? '상시업무 추가'
                : '상시업무 수정'
              : mode === 'add'
                ? '프로젝트 추가'
                : '프로젝트 수정'}
          </h2>
          <button type="button" onClick={onClose} className="task-modal-close" aria-label="닫기">
            ✕
          </button>
        </div>

        <form onSubmit={handleSubmit} className="task-modal-body">
          <TaskFormFields
            variant={variant}
            form={form}
            onChange={setForm}
            sectionOptions={sectionOptions}
            teamMembers={teamMembers}
            idPrefix={`modal-${mode}`}
          />

          <div className="task-form-actions">
            <button type="button" onClick={onClose} className="task-form-btn task-form-btn--ghost">
              취소
            </button>
            <button
              type="submit"
              className={`task-form-btn task-form-btn--primary${isRoutine ? ' is-routine' : ''}`}
            >
              {mode === 'add' ? '추가하기' : '저장하기'}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body,
  );
}
