import type { StageFormData } from '../detail/stageFormTypes';
import { newPeriodEntry } from '../../lib/milestonePeriods';
import type { TeamMember } from '../../types';

interface StageFormFieldsProps {
  variant: 'project' | 'routine';
  form: StageFormData;
  onChange: (next: StageFormData) => void;
  teamMembers?: TeamMember[];
  idPrefix?: string;
}

export function StageFormFields({
  variant,
  form,
  onChange,
  teamMembers = [],
  idPrefix = 'stage-form',
}: StageFormFieldsProps) {
  const isRoutine = variant === 'routine';

  const set = <K extends keyof StageFormData>(field: K, value: StageFormData[K]) =>
    onChange({ ...form, [field]: value });

  const updatePeriodEntry = (id: string, patch: Partial<(typeof form.periodEntries)[0]>) => {
    onChange({
      ...form,
      periodEntries: form.periodEntries.map((entry) => (entry.id === id ? { ...entry, ...patch } : entry)),
    });
  };

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

  return (
    <div className="task-form-fields">
      <div className="task-form-field">
        <label className="task-form-label" htmlFor={`${idPrefix}-title`}>
          단계 제목 *
        </label>
        <input
          id={`${idPrefix}-title`}
          required
          value={form.title}
          onChange={(e) => set('title', e.target.value)}
          className="task-form-input task-form-input--title"
          placeholder="업무 일정 제목"
        />
      </div>

      {isRoutine && (
        <div className="task-form-field">
          <label className="task-form-label" htmlFor={`${idPrefix}-subtitle`}>
            부제목
          </label>
          <input
            id={`${idPrefix}-subtitle`}
            value={form.subtitle}
            onChange={(e) => set('subtitle', e.target.value)}
            className="task-form-input"
            placeholder="업무명 아래 표시 (선택)"
          />
        </div>
      )}

      <div className="task-form-field">
        <label className="task-form-label" htmlFor={`${idPrefix}-progress`}>
          진행률 <span className="task-form-progress-val">{form.progress}%</span>
        </label>
        <input
          id={`${idPrefix}-progress`}
          type="range"
          min={0}
          max={100}
          step={5}
          value={form.progress}
          onChange={(e) => set('progress', Number(e.target.value))}
          className="task-form-range"
        />
      </div>

      <div className="task-form-field">
        <div className="task-form-label-row">
          <span className="task-form-label">수행 기간</span>
          <button
            type="button"
            className="task-form-link-btn"
            onClick={() => onChange({ ...form, periodEntries: [...form.periodEntries, newPeriodEntry()] })}
          >
            + 기간 추가
          </button>
        </div>
        {form.periodEntries.length === 0 ? (
          <p className="task-form-empty">등록된 기간이 없습니다. 보류 후 재개·분기별 수행 등 기간을 추가하세요.</p>
        ) : (
          <div className="task-form-issues">
            {form.periodEntries.map((entry, index) => (
              <div key={entry.id} className="task-form-issue">
                <div className="task-form-label-row">
                  <span className="task-form-label">기간 {index + 1}</span>
                  <button
                    type="button"
                    className="task-form-link-btn task-form-link-btn--danger"
                    onClick={() =>
                      onChange({
                        ...form,
                        periodEntries: form.periodEntries.filter((e) => e.id !== entry.id),
                      })
                    }
                  >
                    삭제
                  </button>
                </div>
                <div className="task-form-row-2">
                  <input
                    type="date"
                    value={entry.startDate}
                    onChange={(e) => updatePeriodEntry(entry.id, { startDate: e.target.value })}
                    className="task-form-input"
                    aria-label={`기간 ${index + 1} 시작일`}
                  />
                  <input
                    type="date"
                    value={entry.dueDate}
                    onChange={(e) => updatePeriodEntry(entry.id, { dueDate: e.target.value })}
                    className="task-form-input"
                    aria-label={`기간 ${index + 1} 종료일`}
                  />
                </div>
                <textarea
                  value={entry.note}
                  onChange={(e) => updatePeriodEntry(entry.id, { note: e.target.value })}
                  rows={2}
                  className="task-form-input task-form-textarea"
                  placeholder="이 기간에 수행한 내용"
                />
              </div>
            ))}
          </div>
        )}
      </div>

      {isRoutine && teamMembers.length > 0 && (
        <div className="task-form-people">
          <div className="task-form-field">
            <label className="task-form-label" htmlFor={`${idPrefix}-pm`}>
              PM
            </label>
            <select
              id={`${idPrefix}-pm`}
              value={form.pmMemberId}
              onChange={(e) => set('pmMemberId', e.target.value)}
              className="task-form-input"
            >
              <option value="">선택 안 함</option>
              {teamMembers.map((m) => (
                <option key={m.id} value={m.id}>
                  {m.name}
                  {m.rank ? ` · ${m.rank}` : ''}
                </option>
              ))}
            </select>
          </div>
          <div className="task-form-field">
            <span className="task-form-label">담당자 (복수 선택)</span>
            <div className="task-form-assignees">
              {teamMembers.map((m) => {
                const checked = form.assigneeMemberIds.includes(m.id);
                return (
                  <label
                    key={m.id}
                    className={`task-form-assignee-chip${checked ? ' is-checked' : ''}`}
                  >
                    <input
                      type="checkbox"
                      className="sr-only"
                      checked={checked}
                      onChange={() => toggleAssignee(m.id)}
                    />
                    {m.name}
                  </label>
                );
              })}
            </div>
          </div>
        </div>
      )}

      <div className="task-form-field">
        <div className="task-form-label-row">
          <span className="task-form-label">링크</span>
          <button
            type="button"
            className="task-form-link-btn"
            onClick={() =>
              onChange({
                ...form,
                links: [...form.links, { label: '', url: '' }],
              })
            }
          >
            + 링크 추가
          </button>
        </div>
        {form.links.length === 0 ? (
          <p className="task-form-empty">등록된 링크가 없습니다.</p>
        ) : (
          <div className="task-form-issues">
            {form.links.map((link, index) => (
              <div key={index} className="task-form-issue">
                <div className="task-form-row-2">
                  <input
                    value={link.label}
                    onChange={(e) => {
                      const links = [...form.links];
                      links[index] = { ...links[index], label: e.target.value };
                      onChange({ ...form, links });
                    }}
                    className="task-form-input"
                    placeholder="표시명"
                  />
                  <input
                    value={link.url}
                    onChange={(e) => {
                      const links = [...form.links];
                      links[index] = { ...links[index], url: e.target.value };
                      onChange({ ...form, links });
                    }}
                    className="task-form-input"
                    placeholder="URL"
                  />
                </div>
                <div className="task-form-issue-actions">
                  <span />
                  <button
                    type="button"
                    className="task-form-link-btn task-form-link-btn--danger"
                    onClick={() =>
                      onChange({
                        ...form,
                        links: form.links.filter((_, i) => i !== index),
                      })
                    }
                  >
                    삭제
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
