import React from "react";
import {
  parseAuditSectionQuestions
} from "../../utils/auditSectionHelpers.js";

function readAnswer(answers, question) {
  if (!question) return "";
  const qid = question.question_id;
  const raw = answers[qid] ?? answers[String(qid)] ?? "";
  return String(raw).trim();
}

function PreviewCell({ value }) {
  const text = String(value || "").trim();
  return <div className="ptw-preview-value">{text || "\u00A0"}</div>;
}

export default function PtwAuditSectionTablePreview({ section, questions = [], answers = {} }) {
  const { metaWho, metaDate, actionRows } = parseAuditSectionQuestions(questions);

  return (
    <div className="ptw-audit-section ptw-audit-section--preview">
      <table className="ptw-doc-job-table ptw-audit-section__table">
        <tbody>
          <tr>
            <td className="ptw-audit-section__meta-cell">
              <span className="ptw-audit-section__inline-label">WHO :</span>
              <PreviewCell value={readAnswer(answers, metaWho)} />
            </td>
            <td className="ptw-audit-section__meta-cell">
              <span className="ptw-audit-section__inline-label">DATE :</span>
              <PreviewCell value={readAnswer(answers, metaDate)} />
            </td>
          </tr>
        </tbody>
      </table>

      <table className="ptw-doc-job-table ptw-audit-section__table ptw-audit-section__actions">
        <colgroup>
          <col className="ptw-audit-section__col-action" />
          <col className="ptw-audit-section__col-who" />
          <col className="ptw-audit-section__col-when" />
        </colgroup>
        <thead>
          <tr>
            <th className="ptw-doc-job-table__label">ACTION TO BE IMPLEMENTED</th>
            <th className="ptw-doc-job-table__label">WHO</th>
            <th className="ptw-doc-job-table__label">WHEN</th>
          </tr>
        </thead>
        <tbody>
          {actionRows.map((row, index) => (
            <tr key={`audit-action-preview-${index}`}>
              <td>
                <PreviewCell value={readAnswer(answers, row.description)} />
              </td>
              <td>
                <PreviewCell value={readAnswer(answers, row.who)} />
              </td>
              <td>
                <PreviewCell value={readAnswer(answers, row.when)} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
