import React from "react";
import { formatMgmtDateTime } from "../../../utils/ptwMgmtHelpers.jsx";

export const blankSection = {
  title: "",
  section_parent_id: "",
  created_by: ""
};

export function buildSectionPayload(draft) {
  const payload = {};
  if (draft.title?.trim()) payload.title = draft.title.trim();
  if (draft.section_parent_id) payload.section_parent_id = Number(draft.section_parent_id);
  if (draft.created_by) payload.created_by = Number(draft.created_by);
  return payload;
}

export function draftFromRow(row) {
  return {
    title: row.title ?? "",
    section_parent_id:
      row.section_parent_id != null ? String(row.section_parent_id) : "",
    created_by: row.created_by != null ? String(row.created_by) : ""
  };
}

export function normalizeSectionRow(row) {
  if (!row || typeof row !== "object") return null;
  const sectionId = Number(row.section_id);
  return {
    ...row,
    section_id: Number.isFinite(sectionId) ? sectionId : row.section_id,
    section_parent_id:
      row.section_parent_id != null && row.section_parent_id !== ""
        ? Number(row.section_parent_id)
        : null,
    created_by:
      row.created_by != null && row.created_by !== ""
        ? Number(row.created_by)
        : null
  };
}

export function SectionFields({ draft, setDraft }) {
  return (
    <div className="ptw-mgmt-form-grid">
      <label className="ptw-mgmt-field ptw-mgmt-field--span2">
        <span className="ptw-mgmt-field__label">
          Section title <em className="ptw-mgmt-required">*</em>
        </span>
        <input
          className="ptw-mgmt-input"
          value={draft.title}
          onChange={(e) => setDraft((prev) => ({ ...prev, title: e.target.value }))}
        />
      </label>
      <label className="ptw-mgmt-field">
        <span className="ptw-mgmt-field__label">Parent section ID</span>
        <input
          className="ptw-mgmt-input"
          type="number"
          min="1"
          value={draft.section_parent_id}
          onChange={(e) => setDraft((prev) => ({ ...prev, section_parent_id: e.target.value }))}
        />
      </label>
      <label className="ptw-mgmt-field">
        <span className="ptw-mgmt-field__label">Created by (user ID)</span>
        <input
          className="ptw-mgmt-input"
          type="number"
          min="1"
          value={draft.created_by}
          onChange={(e) => setDraft((prev) => ({ ...prev, created_by: e.target.value }))}
        />
      </label>
    </div>
  );
}

function SectionQuestionsReadOnly({ questions }) {
  const list = Array.isArray(questions) ? questions : [];
  if (!list.length) {
    return (
      <div className="ptw-section-detail__empty">
        <p>No questions mapped to this section.</p>
      </div>
    );
  }
  return (
    <ol className="ptw-section-detail__question-list ptw-section-detail__question-list--readonly">
      {list.map((q, index) => (
        <li key={q.question_id} className="ptw-section-detail__question-item">
          <span className="ptw-section-detail__question-index">{index + 1}</span>
          <div className="ptw-section-detail__question-body">
            <div className="ptw-section-detail__question-head">
              <span className="ptw-mgmt-tag ptw-mgmt-tag--muted">#{q.question_id}</span>
              {q.question_type ? (
                <span className="ptw-mgmt-tag">{q.question_type}</span>
              ) : null}
            </div>
            <p className="ptw-section-detail__question-text">{q.question || "—"}</p>
          </div>
        </li>
      ))}
    </ol>
  );
}

export function SectionDetailView({ row, questionCount }) {
  const questions = Array.isArray(row.questions) ? row.questions : [];
  const count = questions.length || questionCount || 0;

  return (
    <div className="ptw-section-detail">
      <div className="ptw-section-detail__stats">
        <div className="ptw-section-detail__stat">
          <span className="ptw-section-detail__stat-label">Questions</span>
          <strong className="ptw-section-detail__stat-value">{count}</strong>
        </div>
        <div className="ptw-section-detail__stat">
          <span className="ptw-section-detail__stat-label">Parent section</span>
          <strong className="ptw-section-detail__stat-value">
            {row.section_parent_id ?? "—"}
          </strong>
        </div>
        <div className="ptw-section-detail__stat">
          <span className="ptw-section-detail__stat-label">Created by</span>
          <strong className="ptw-section-detail__stat-value">
            {row.created_by ?? "—"}
          </strong>
        </div>
        <div className="ptw-section-detail__stat">
          <span className="ptw-section-detail__stat-label">Created</span>
          <strong className="ptw-section-detail__stat-value ptw-section-detail__stat-value--sm">
            {formatMgmtDateTime(row.created_date)}
          </strong>
        </div>
      </div>

      <div className="ptw-section-detail__questions">
        <div className="ptw-section-detail__questions-head">
          <h4 className="ptw-section-detail__questions-title">Mapped questions</h4>
          <span className="ptw-section-detail__questions-count">
            {count} {count === 1 ? "item" : "items"}
          </span>
        </div>
        <SectionQuestionsReadOnly questions={questions} />
      </div>
    </div>
  );
}

export function MgmtBreadcrumb({ onBack, label = "Back to list" }) {
  return (
    <nav className="ptw-mgmt-breadcrumb" aria-label="Breadcrumb">
      <button type="button" className="ptw-mgmt-breadcrumb__link" onClick={onBack}>
        ← {label}
      </button>
    </nav>
  );
}
