import { useState } from 'react';
import { createPortal } from 'react-dom';

export interface OverviewFormData {
  description: string;
  detailDescription: string;
}

interface OverviewEditModalProps {
  initial: OverviewFormData;
  onSave: (data: OverviewFormData) => Promise<void>;
  onClose: () => void;
  saving?: boolean;
}

export function OverviewEditModal({
  initial,
  onSave,
  onClose,
  saving,
}: OverviewEditModalProps) {
  const [form, setForm] = useState<OverviewFormData>(initial);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await onSave(form);
  };

  return createPortal(
    <div className="task-modal-overlay" onClick={onClose}>
      <div className="task-modal-shell" style={{ width: 'min(480px, 94vw)' }} onClick={(e) => e.stopPropagation()}>
        <div className="task-modal-head">
          <h2 className="task-modal-title">개요 수정</h2>
          <button type="button" onClick={onClose} className="task-modal-close" aria-label="닫기">
            ✕
          </button>
        </div>
        <form onSubmit={handleSubmit} className="task-modal-body">
          <div className="task-form-fields">
            <div className="task-form-field">
              <label className="task-form-label" htmlFor="overview-desc">
                개요
              </label>
              <textarea
                id="overview-desc"
                value={form.description}
                onChange={(e) => setForm((p) => ({ ...p, 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="overview-detail">
                상세내용
              </label>
              <textarea
                id="overview-detail"
                value={form.detailDescription}
                onChange={(e) => setForm((p) => ({ ...p, detailDescription: e.target.value }))}
                rows={5}
                className="task-form-input task-form-textarea task-form-textarea--tall"
                placeholder="상세 내용"
              />
            </div>
          </div>
          <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" disabled={saving}>
              {saving ? '저장 중…' : '저장'}
            </button>
          </div>
        </form>
      </div>
    </div>,
    document.body,
  );
}
