import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { apiClient, getApiErrorMessage } from '../../lib/apiClient';
import { invalidateTaskCaches } from '../../lib/taskQueryCache';
import type { Milestone, TaskDetail } from '../../types';

export function TaskFeedbackSection({
  taskId,
  milestones,
  details,
}: {
  taskId: string;
  milestones: Milestone[];
  details: TaskDetail[];
}) {
  const queryClient = useQueryClient();
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [adding, setAdding] = useState(false);
  const [addMilestoneId, setAddMilestoneId] = useState(milestones[0]?.id ?? '');
  const [addContent, setAddContent] = useState('');
  const [addAuthor, setAddAuthor] = useState('');
  const [editForms, setEditForms] = useState<Record<string, { content: string; authorName: string }>>({});

  const sorted = [...details].sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
  );

  const milestoneTitle = (id: string | null) =>
    milestones.find((m) => m.id === id)?.title ?? '—';

  const startEdit = (detail: TaskDetail) => {
    setExpandedId(detail.id);
    setEditForms((prev) => ({
      ...prev,
      [detail.id]: {
        content: detail.content,
        authorName: detail.authorName ?? detail.author?.name ?? '',
      },
    }));
  };

  const saveEdit = async (detailId: string) => {
    const form = editForms[detailId];
    if (!form?.content.trim()) return;
    try {
      await apiClient.patch(`/details/item/${detailId}`, {
        content: form.content.trim(),
        authorName: form.authorName.trim() || null,
      });
      invalidateTaskCaches(queryClient, taskId);
      setExpandedId(null);
    } catch (err: unknown) {
      alert(getApiErrorMessage(err, '피드백 저장에 실패했습니다.'));
    }
  };

  const remove = async (detailId: string) => {
    if (!window.confirm('피드백을 삭제하시겠습니까?')) return;
    try {
      await apiClient.delete(`/details/item/${detailId}`);
      invalidateTaskCaches(queryClient, taskId);
    } catch (err: unknown) {
      alert(getApiErrorMessage(err, '삭제에 실패했습니다.'));
    }
  };

  const addFeedback = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!addMilestoneId || !addContent.trim() || !addAuthor.trim()) return;
    try {
      await apiClient.post(`/details/${taskId}`, {
        content: addContent.trim(),
        authorName: addAuthor.trim(),
        milestoneId: addMilestoneId,
      });
      invalidateTaskCaches(queryClient, taskId);
      setAdding(false);
      setAddContent('');
    } catch (err: unknown) {
      alert(getApiErrorMessage(err, '피드백 추가에 실패했습니다.'));
    }
  };

  return (
    <section className="task-manager-section">
      <div className="task-manager-section__head">
        <h4 className="task-manager-section__title">피드백</h4>
        <button
          type="button"
          className="task-form-link-btn"
          disabled={milestones.length === 0}
          onClick={() => setAdding(true)}
        >
          + 피드백 추가
        </button>
      </div>

      {milestones.length === 0 && (
        <p className="task-form-empty">피드백을 추가하려면 먼저 업무 일정을 등록하세요.</p>
      )}

      {adding && milestones.length > 0 && (
        <form className="task-manager-subpanel task-manager-subpanel--new" onSubmit={addFeedback}>
          <div className="task-form-field">
            <label className="task-form-label">연결 일정</label>
            <select
              value={addMilestoneId}
              onChange={(e) => setAddMilestoneId(e.target.value)}
              className="task-form-input"
            >
              {milestones.map((m) => (
                <option key={m.id} value={m.id}>
                  {m.title}
                </option>
              ))}
            </select>
          </div>
          <div className="task-form-field">
            <label className="task-form-label">피드백 내용 *</label>
            <textarea
              required
              value={addContent}
              onChange={(e) => setAddContent(e.target.value)}
              rows={3}
              className="task-form-input task-form-textarea"
            />
          </div>
          <div className="task-form-field">
            <label className="task-form-label">작성자 *</label>
            <input
              required
              value={addAuthor}
              onChange={(e) => setAddAuthor(e.target.value)}
              className="task-form-input"
            />
          </div>
          <div className="task-manager-panel__actions">
            <button type="button" className="task-form-btn task-form-btn--ghost" onClick={() => setAdding(false)}>
              취소
            </button>
            <button type="submit" className="task-form-btn task-form-btn--primary">
              추가
            </button>
          </div>
        </form>
      )}

      {sorted.length === 0 && !adding && milestones.length > 0 && (
        <p className="task-form-empty">등록된 피드백이 없습니다.</p>
      )}

      {sorted.map((detail) => {
        const editing = expandedId === detail.id;
        const form = editForms[detail.id] ?? {
          content: detail.content,
          authorName: detail.authorName ?? detail.author?.name ?? '',
        };
        return (
          <article key={detail.id} className={`task-manager-subrow${editing ? ' is-expanded' : ''}`}>
            <button
              type="button"
              className="task-manager-subrow__head"
              onClick={() => (editing ? setExpandedId(null) : startEdit(detail))}
            >
              <span className="task-manager-row__chevron" aria-hidden="true">
                ›
              </span>
              <span className="task-manager-subrow__title truncate">{detail.content}</span>
              <span className="task-manager-subrow__meta">
                <span
                  className={`task-manager-badge task-manager-badge--status${
                    !detail.milestoneId ? ' is-legacy' : ''
                  }`}
                >
                  {!detail.milestoneId ? '레거시·일정 미연결' : milestoneTitle(detail.milestoneId)}
                </span>
              </span>
            </button>
            {editing && (
              <div className="task-manager-subpanel">
                <div className="task-form-field">
                  <label className="task-form-label">피드백 내용</label>
                  <textarea
                    value={form.content}
                    onChange={(e) =>
                      setEditForms((prev) => ({
                        ...prev,
                        [detail.id]: { ...form, content: e.target.value },
                      }))
                    }
                    rows={3}
                    className="task-form-input task-form-textarea"
                  />
                </div>
                <div className="task-form-field">
                  <label className="task-form-label">작성자</label>
                  <input
                    value={form.authorName}
                    onChange={(e) =>
                      setEditForms((prev) => ({
                        ...prev,
                        [detail.id]: { ...form, authorName: e.target.value },
                      }))
                    }
                    className="task-form-input"
                  />
                </div>
                <div className="task-manager-panel__actions">
                  <button
                    type="button"
                    className="task-form-btn task-form-btn--danger"
                    onClick={() => remove(detail.id)}
                  >
                    삭제
                  </button>
                  <button
                    type="button"
                    className="task-form-btn task-form-btn--primary"
                    onClick={() => saveEdit(detail.id)}
                  >
                    저장
                  </button>
                </div>
              </div>
            )}
          </article>
        );
      })}
    </section>
  );
}
