import { useState } from 'react';
import { createPortal } from 'react-dom';
import type { Task, TeamMember, TaskIssueEntry } from '../../types';
import { normalizeTaskType } from '../../lib/taskType';
import { newIssueEntry, parseIssueEntries } from '../../lib/taskIssues';
import { getRoutineCategory, routineCategoryOptions } from '../../lib/routineCategories';

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

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

interface TaskModalProps {
  mode: 'add' | 'edit';
  /** project: 실행과제 전용 / routine: 기반업무(상시) 전용 */
  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 = 'HR',
  defaultCategory = '채용 운영',
  defaultQuarter = '2026-Q2',
  sectionOptions,
  teamMembers = [],
  onSave,
  onClose,
}: TaskModalProps) {
  const isRoutine = variant === 'routine';
  const toDateInput = (iso: string | null | undefined) => {
    if (!iso) return '';
    return new Date(iso).toISOString().slice(0, 10);
  };

  const [form, setForm] = useState<TaskFormData>({
    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 ?? '',
    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) ?? [],
  });

  const toggleAssignee = (memberId: string) => {
    setForm((prev) => {
      const has = prev.assigneeMemberIds.includes(memberId);
      return {
        ...prev,
        assigneeMemberIds: has
          ? prev.assigneeMemberIds.filter((id) => id !== memberId)
          : [...prev.assigneeMemberIds, memberId],
      };
    });
  };

  const set = <K extends keyof TaskFormData>(field: K, value: TaskFormData[K]) =>
    setForm(prev => ({ ...prev, [field]: value }));

  const updateIssueEntry = (id: string, patch: Partial<TaskIssueEntry>) => {
    setForm((prev) => ({
      ...prev,
      issueEntries: prev.issueEntries.map((entry) =>
        entry.id === id ? { ...entry, ...patch } : entry,
      ),
    }));
  };

  const addIssueEntry = () => {
    setForm((prev) => ({
      ...prev,
      issueEntries: [...prev.issueEntries, newIssueEntry()],
    }));
  };

  const removeIssueEntry = (id: string) => {
    setForm((prev) => ({
      ...prev,
      issueEntries: prev.issueEntries.filter((entry) => entry.id !== id),
    }));
  };

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

  return createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50"
      onClick={onClose}
    >
      <div
        className="bg-white rounded-2xl shadow-2xl w-[540px] max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h2 className="text-2xl font-black text-gray-800">
            {isRoutine
              ? (mode === 'add' ? '✚ 상시업무 추가' : '✏ 상시업무 수정')
              : (mode === 'add' ? '✚ 프로젝트 추가' : '✏ 프로젝트 수정')}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-2xl leading-none transition-colors"
          >
            ✕
          </button>
        </div>

        <form onSubmit={handleSubmit} className="px-6 py-5 space-y-4">
          {/* 제목 */}
          <div>
            <label className="block text-sm font-bold text-gray-500 mb-1.5">제목 *</label>
            <input
              required
              value={form.title}
              onChange={(e) => set('title', e.target.value)}
              className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-lg outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition"
              placeholder="업무 제목을 입력하세요"
            />
          </div>

          {/* 대분류 (상시업무) / 소속 부문 (프로젝트) */}
          <div>
            <label className="block text-sm font-bold text-gray-500 mb-1.5">
              {isRoutine ? '대분류' : '소속 부문'}
            </label>
            {isRoutine ? (
              <select
                value={form.category}
                onChange={(e) => set('category', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:ring-2 transition bg-white focus:border-emerald-400 focus:ring-emerald-100"
              >
                {routineCategoryOptions().map((opt) => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            ) : (
              <select
                value={form.section}
                onChange={(e) => set('section', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:ring-2 transition bg-white focus:border-blue-400 focus:ring-blue-100"
              >
                {(sectionOptions ?? [
                  { value: 'HR', label: 'HR' },
                  { value: '운영관리', label: '운영관리' },
                ]).map((opt) => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            )}
          </div>

          {/* 상태 + 진행률 (프로젝트만) */}
          {!isRoutine && (
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-bold text-gray-500 mb-1.5">상태</label>
              <select
                value={form.status}
                onChange={(e) => set('status', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition bg-white"
              >
                {STATUS_OPTIONS.map((s) => (
                  <option key={s.value} value={s.value}>{s.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-bold text-gray-500 mb-1.5">
                진행률
                <span className="ml-2 font-black text-gray-800">{form.progress}%</span>
              </label>
              <div className="flex items-center gap-3 pt-2">
                <input
                  type="range"
                  min={0}
                  max={100}
                  step={5}
                  value={form.progress}
                  onChange={(e) => set('progress', Number(e.target.value))}
                  className="flex-1 accent-blue-500"
                />
              </div>
            </div>
          </div>
          )}

          {/* 상태 (상시업무) */}
          {isRoutine && (
            <div>
              <label className="block text-sm font-bold text-gray-500 mb-1.5">상태</label>
              <select
                value={form.status}
                onChange={(e) => set('status', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 transition bg-white"
              >
                {STATUS_OPTIONS.map((s) => (
                  <option key={s.value} value={s.value}>{s.label}</option>
                ))}
              </select>
            </div>
          )}

          {/* 내용 */}
          <div>
            <label className="block text-sm font-bold text-gray-500 mb-1.5">내용</label>
            <textarea
              value={form.description}
              onChange={(e) => set('description', e.target.value)}
              rows={3}
              className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-base outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 resize-none transition"
              placeholder="내용을 입력하세요"
            />
          </div>

          {/* PM + 담당자 */}
          {teamMembers.length > 0 && (
            <div className="space-y-3 rounded-xl border border-emerald-100 bg-emerald-50/40 p-4">
              <div>
                <label className="block text-sm font-bold text-gray-500 mb-1.5">PM</label>
                <select
                  value={form.pmMemberId}
                  onChange={(e) => set('pmMemberId', e.target.value)}
                  className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 transition bg-white"
                >
                  <option value="">선택 안 함</option>
                  {teamMembers.map((m) => (
                    <option key={m.id} value={m.id}>
                      {m.name}{m.rank ? ` · ${m.rank}` : ''}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-bold text-gray-500 mb-1.5">담당자 (복수 선택)</label>
                <div className="flex flex-wrap gap-2">
                  {teamMembers.map((m) => {
                    const checked = form.assigneeMemberIds.includes(m.id);
                    return (
                      <label
                        key={m.id}
                        className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border cursor-pointer select-none text-sm font-semibold transition ${
                          checked
                            ? 'bg-emerald-600 text-white border-emerald-600'
                            : 'bg-white text-gray-600 border-gray-200 hover:border-emerald-300'
                        }`}
                      >
                        <input
                          type="checkbox"
                          className="sr-only"
                          checked={checked}
                          onChange={() => toggleAssignee(m.id)}
                        />
                        {m.name}
                      </label>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {/* 프로젝트 기간 */}
          {!isRoutine && (
          <div>
            <label className="block text-sm font-bold text-gray-500 mb-1.5">기간</label>
            <div className="grid grid-cols-2 gap-3">
              <input
                type="date"
                value={form.startDate}
                onChange={(e) => set('startDate', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition"
              />
              <input
                type="date"
                value={form.dueDate}
                onChange={(e) => set('dueDate', e.target.value)}
                className="w-full border border-gray-200 rounded-xl px-4 py-2.5 outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition"
              />
            </div>
          </div>
          )}

          {/* 이슈 메모 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-bold text-gray-500">이슈 메모</label>
              <button
                type="button"
                onClick={addIssueEntry}
                className="text-xs font-bold text-blue-600 hover:text-blue-700 px-2 py-1 rounded-lg hover:bg-blue-50 transition"
              >
                + 이슈 추가
              </button>
            </div>
            {form.issueEntries.length === 0 ? (
              <p className="text-sm text-gray-400 rounded-xl border border-dashed border-gray-200 px-4 py-3 text-center">
                등록된 이슈가 없습니다. 위 버튼으로 추가하세요.
              </p>
            ) : (
              <div className="space-y-2">
                {form.issueEntries.map((entry, index) => (
                  <div
                    key={entry.id}
                    className="rounded-xl border border-gray-200 bg-gray-50/60 p-3 space-y-2"
                  >
                    <textarea
                      value={entry.text}
                      onChange={(e) => updateIssueEntry(entry.id, { text: e.target.value })}
                      rows={2}
                      className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 resize-none transition bg-white"
                      placeholder={`[날짜] 이슈 내용 (${index + 1})`}
                    />
                    <div className="flex items-center justify-between gap-2">
                      <label className="flex items-center gap-1.5 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={entry.showOnCard}
                          onChange={(e) => updateIssueEntry(entry.id, { showOnCard: e.target.checked })}
                          className="w-4 h-4 accent-blue-500 cursor-pointer"
                        />
                        <span className="text-xs font-semibold text-gray-500">카드 표시</span>
                      </label>
                      <button
                        type="button"
                        onClick={() => removeIssueEntry(entry.id)}
                        className="text-xs font-bold text-red-500 hover:text-red-600 px-2 py-1 rounded-lg hover:bg-red-50 transition"
                      >
                        삭제
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 버튼 */}
          <div className="flex justify-end gap-2 pt-2 pb-1">
            <button
              type="button"
              onClick={onClose}
              className="px-5 py-2.5 rounded-xl border border-gray-200 text-gray-600 font-semibold hover:bg-gray-50 transition"
            >
              취소
            </button>
            <button
              type="submit"
              className={`px-6 py-2.5 rounded-xl text-white font-bold transition ${
                isRoutine ? 'bg-emerald-700 hover:bg-emerald-800' : 'bg-blue-600 hover:bg-blue-700'
              }`}
            >
              {mode === 'add' ? '추가하기' : '저장하기'}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body
  );
}
