import type { TaskFormData } from '../../lib/taskFormState';
import { STATUS_OPTIONS } from '../../lib/taskFormState';
import { routineCategoryOptions } from '../../lib/routineCategories';
import { newIssueEntry } from '../../lib/taskIssues';
import type { TeamMember } from '../../types';

type SectionOption = { value: string; label: string };

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

export function TaskFormFields({
  variant,
  form,
  onChange,
  sectionOptions,
  teamMembers = [],
  idPrefix = 'task-form',
}: TaskFormFieldsProps) {
  const isRoutine = variant === 'routine';

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

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

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

  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>

      <div className="task-form-field">
        <label className="task-form-label" htmlFor={`${idPrefix}-section`}>
          {isRoutine ? '대분류' : '소속 부문'}
        </label>
        {isRoutine ? (
          <select
            id={`${idPrefix}-section`}
            value={form.category}
            onChange={(e) => set('category', e.target.value)}
            className="task-form-input"
          >
            {routineCategoryOptions().map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        ) : (
          <select
            id={`${idPrefix}-section`}
            value={form.section}
            onChange={(e) => set('section', e.target.value)}
            className="task-form-input"
          >
            {(sectionOptions ?? [
              { value: '인사관리', label: '인사관리' },
              { value: '운영관리', label: '총무관리' },
            ]).map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        )}
      </div>

      {!isRoutine && (
        <div className="task-form-row-2">
          <div className="task-form-field">
            <label className="task-form-label" htmlFor={`${idPrefix}-status`}>
              상태
            </label>
            <select
              id={`${idPrefix}-status`}
              value={form.status}
              onChange={(e) => set('status', e.target.value)}
              className="task-form-input"
            >
              {STATUS_OPTIONS.map((s) => (
                <option key={s.value} value={s.value}>
                  {s.label}
                </option>
              ))}
            </select>
          </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>
      )}

      {isRoutine && (
        <div className="task-form-field">
          <label className="task-form-label" htmlFor={`${idPrefix}-status`}>
            상태
          </label>
          <select
            id={`${idPrefix}-status`}
            value={form.status}
            onChange={(e) => set('status', e.target.value)}
            className="task-form-input"
          >
            {STATUS_OPTIONS.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>
      )}

      {isRoutine ? (
        <div className="task-form-field">
          <label className="task-form-label" htmlFor={`${idPrefix}-desc`}>
            내용
          </label>
          <textarea
            id={`${idPrefix}-desc`}
            value={form.description}
            onChange={(e) => set('description', e.target.value)}
            rows={3}
            className="task-form-input task-form-textarea"
            placeholder="내용을 입력하세요"
          />
        </div>
      ) : (
        <>
          <div className="task-form-field">
            <label className="task-form-label" htmlFor={`${idPrefix}-overview`}>
              개요
            </label>
            <textarea
              id={`${idPrefix}-overview`}
              value={form.description}
              onChange={(e) => set('description', e.target.value)}
              rows={2}
              className="task-form-input task-form-textarea"
              placeholder="프로젝트 개요를 입력하세요"
            />
          </div>
          <div className="task-form-field">
            <label className="task-form-label" htmlFor={`${idPrefix}-detail`}>
              상세내용
            </label>
            <textarea
              id={`${idPrefix}-detail`}
              value={form.detailDescription}
              onChange={(e) => set('detailDescription', e.target.value)}
              rows={4}
              className="task-form-input task-form-textarea task-form-textarea--tall"
              placeholder="상세 내용을 입력하세요"
            />
          </div>
        </>
      )}

      {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>
      )}

      {!isRoutine && (
        <div className="task-form-field">
          <span className="task-form-label">기간</span>
          <div className="task-form-row-2">
            <input
              type="date"
              value={form.startDate}
              onChange={(e) => set('startDate', e.target.value)}
              className="task-form-input"
              aria-label="시작일"
            />
            <input
              type="date"
              value={form.dueDate}
              onChange={(e) => set('dueDate', e.target.value)}
              className="task-form-input"
              aria-label="종료일"
            />
          </div>
        </div>
      )}

      <div className="task-form-field">
        <div className="task-form-label-row">
          <span className="task-form-label">이슈 메모</span>
          <button
            type="button"
            onClick={() => onChange({ ...form, issueEntries: [...form.issueEntries, newIssueEntry()] })}
            className="task-form-link-btn"
          >
            + 이슈 추가
          </button>
        </div>
        {form.issueEntries.length === 0 ? (
          <p className="task-form-empty">등록된 이슈가 없습니다.</p>
        ) : (
          <div className="task-form-issues">
            {form.issueEntries.map((entry, index) => (
              <div key={entry.id} className="task-form-issue">
                <textarea
                  value={entry.text}
                  onChange={(e) => updateIssueEntry(entry.id, { text: e.target.value })}
                  rows={2}
                  className="task-form-input task-form-textarea"
                  placeholder={`이슈 내용 (${index + 1})`}
                />
                <div className="task-form-issue-actions">
                  <label className="task-form-issue-date">
                    <span className="task-form-issue-date-label">발생일</span>
                    <input
                      type="date"
                      value={entry.occurredOn ?? ''}
                      onChange={(e) => updateIssueEntry(entry.id, { occurredOn: e.target.value || null })}
                      className="task-form-input task-form-issue-date-input"
                      aria-label={`이슈 ${index + 1} 발생일`}
                    />
                  </label>
                  <label className="task-form-issue-check">
                    <input
                      type="checkbox"
                      checked={entry.showOnCard}
                      onChange={(e) => updateIssueEntry(entry.id, { showOnCard: e.target.checked })}
                    />
                    카드 표시
                  </label>
                  <button
                    type="button"
                    onClick={() =>
                      onChange({
                        ...form,
                        issueEntries: form.issueEntries.filter((e) => e.id !== entry.id),
                      })
                    }
                    className="task-form-link-btn task-form-link-btn--danger"
                  >
                    삭제
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
