import { useState } from 'react';
import { createPortal } from 'react-dom';
import type { TaskDetail } from '../../types';

export interface FeedbackFormData {
  content: string;
  authorName: string;
}

interface FeedbackModalProps {
  mode: 'add' | 'edit';
  detail?: TaskDetail;
  defaultAuthorName?: string;
  onSave: (data: FeedbackFormData) => Promise<void>;
  onClose: () => void;
  saving?: boolean;
}

export function FeedbackModal({
  mode,
  detail,
  defaultAuthorName = '',
  onSave,
  onClose,
  saving,
}: FeedbackModalProps) {
  const [form, setForm] = useState<FeedbackFormData>({
    content: detail?.content ?? '',
    authorName: detail?.authorName ?? detail?.author?.name ?? defaultAuthorName,
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.content.trim()) return;
    if (mode === 'add' && !form.authorName.trim()) return;
    await onSave(form);
  };

  return createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4"
      onMouseDown={onClose}
    >
      <form
        className="flex w-full max-w-md flex-col overflow-hidden rounded-2xl bg-white shadow-2xl"
        onMouseDown={(e) => e.stopPropagation()}
        onSubmit={handleSubmit}
      >
        <div className="border-b border-slate-100 px-6 py-4">
          <h2 className="text-xl font-black text-slate-800">
            {mode === 'add' ? '피드백 추가' : '피드백 수정'}
          </h2>
        </div>

        <div className="space-y-4 px-6 py-4">
          <label className="block">
            <span className="mb-1 block text-sm font-bold text-slate-500">피드백 내용 *</span>
            <textarea
              required
              autoFocus
              value={form.content}
              onChange={(e) => setForm((p) => ({ ...p, content: e.target.value }))}
              rows={4}
              className="w-full resize-none rounded-lg border border-slate-200 px-3 py-2 text-base focus:border-emerald-400 focus:outline-none"
              placeholder="피드백을 입력하세요"
            />
          </label>

          <label className="block">
            <span className="mb-1 block text-sm font-bold text-slate-500">
              이름 {mode === 'add' ? '*' : ''}
            </span>
            <input
              required={mode === 'add'}
              value={form.authorName}
              onChange={(e) => setForm((p) => ({ ...p, authorName: e.target.value }))}
              className="w-full rounded-lg border border-slate-200 px-3 py-2 text-base focus:border-emerald-400 focus:outline-none"
              placeholder="작성자 이름"
            />
          </label>
        </div>

        <div className="flex justify-end gap-2 border-t border-slate-100 px-6 py-4">
          <button
            type="button"
            onClick={onClose}
            disabled={saving}
            className="rounded-lg px-4 py-2 text-sm font-bold text-slate-500 hover:bg-slate-50"
          >
            취소
          </button>
          <button
            type="submit"
            disabled={saving || !form.content.trim() || (mode === 'add' && !form.authorName.trim())}
            className="rounded-lg bg-emerald-600 px-5 py-2 text-sm font-bold text-white hover:bg-emerald-700 disabled:opacity-50"
          >
            {saving ? '저장 중…' : mode === 'add' ? '추가' : '저장'}
          </button>
        </div>
      </form>
    </div>,
    document.body,
  );
}
