import React from "react";
import FileUploadField from "../common/FileUploadField.jsx";
import PtwDocumentQuestionsTable from "./PtwDocumentQuestionsTable.jsx";
import PtwAuditSectionTable from "./PtwAuditSectionTable.jsx";
import PtwRiskAssessmentTable from "./PtwRiskAssessmentTable.jsx";
import { SECTION_KIND } from "../../utils/sectionTypeHelpers.js";
import { shouldUseAuditSectionLayout } from "../../utils/auditSectionHelpers.js";
import { shouldUseRiskAssessmentSectionLayout } from "../../utils/riskAssessmentHelpers.js";
import { PTW_MAX_UPLOAD_MB } from "../../utils/uploadLimits.js";

const PRECAUTION_WARNING =
  "THIS PERMIT IS ONLY VALID WHEN ALL SECTIONS ARE COMPLETE. DO NOT PROCEED WITH YOUR WORK UNTIL YOUR PERMIT HAS BEEN AUTHORISED BY THE RELEVANT MEMBERS OF STAFF AND THE \"NO\" SCORING FROM THE PRECAUTION CHECKLIST HAVE BEEN SOLVED !";

const CHECKLIST_HEADING =
  "PLEASE ANSWER THE FOLLOWING QUESTIONS TRUTHFULLY, IF IN DOUBT, CONSULT YOUR MANAGER FOR ASSISTANCE.";

/** Section headers come only from ptw_section_details.title — never from question types. */
function formatSectionTitle(title) {
  const raw = String(title || "").trim();
  return raw ? raw.toUpperCase() : "SECTION";
}

function shouldShowPrecautionWarning(sectionKind) {
  return sectionKind === SECTION_KIND.STANDARD || sectionKind === SECTION_KIND.RISK;
}

export default function PtwDocumentSection({
  section,
  sectionKind,
  sectionSkipable = false,
  questions = [],
  questionTypeOptions,
  answers,
  setAnswer,
  mediaByQuestion,
  setMedia,
  showPermitVideoUpload = false,
  permitVideoUploaded = false,
  onPermitVideoUpload,
  permitVideoInputRef,
  skipChoice,
  setSkipChoice,
  skipReference,
  setSkipReference,
  skipNotes,
  setSkipNotes,
  riskVisibleRowCount,
  onRiskVisibleRowCountChange,
  formMeta = null,
  formTypes = []
}) {
  const title = formatSectionTitle(section?.title);
  const useAuditLayout = shouldUseAuditSectionLayout(section, formMeta, formTypes);
  const useRiskLayout =
    !useAuditLayout && shouldUseRiskAssessmentSectionLayout(section, questions);
  const hideQuestions = sectionSkipable && skipChoice === "yes";
  const showChecklistHeader = sectionKind !== SECTION_KIND.GENERAL;
  const showQuestionNumbers = sectionKind !== SECTION_KIND.GENERAL;
  const isRiskSection = sectionKind === SECTION_KIND.RISK;
  const completingSection = !sectionSkipable || skipChoice === "no";
  const awaitingSkipChoice = sectionSkipable && !skipChoice;
  const permitVideoLabel = `Permit video * (max ${PTW_MAX_UPLOAD_MB} MB)`;
  const videoInputProps = permitVideoInputRef ? { inputRef: permitVideoInputRef } : {};

  const showQuestionTable =
    !hideQuestions &&
    !awaitingSkipChoice &&
    questions.length > 0 &&
    !useAuditLayout &&
    !useRiskLayout;

  const auditTable =
    !hideQuestions && !awaitingSkipChoice && questions.length > 0 && useAuditLayout ? (
      <PtwAuditSectionTable
        section={section}
        questions={questions}
        answers={answers}
        onChange={setAnswer}
      />
    ) : null;

  const riskTable =
    !hideQuestions && !awaitingSkipChoice && questions.length > 0 && useRiskLayout ? (
      <PtwRiskAssessmentTable
        section={section}
        questions={questions}
        questionTypeOptions={questionTypeOptions}
        answers={answers}
        onChange={setAnswer}
        visibleRowCount={riskVisibleRowCount}
        onVisibleRowCountChange={onRiskVisibleRowCountChange}
      />
    ) : null;

  const questionTable = showQuestionTable ? (
    <PtwDocumentQuestionsTable
      questions={questions}
      questionTypeOptions={questionTypeOptions}
      answers={answers}
      onChange={setAnswer}
      mediaByQuestion={mediaByQuestion}
      onMediaChange={setMedia}
      showHeader={showChecklistHeader}
      showNumber={showQuestionNumbers}
      heading={CHECKLIST_HEADING}
    />
  ) : null;

  return (
    <div className="ptw-doc-section">
      {showPermitVideoUpload ? (
        <div className="ptw-doc-media-row ptw-doc-media-row--top">
          <FileUploadField
            label={permitVideoLabel}
            multiple={false}
            accept="video/*"
            onChange={onPermitVideoUpload}
            hint="Upload once for this permit. The same video applies to all sections."
            {...videoInputProps}
          />
        </div>
      ) : null}

      {permitVideoUploaded && !showPermitVideoUpload ? (
        <p className="ptw-doc-checklist-gate ptw-doc-checklist-gate--inline">
          Permit video uploaded — no need to upload again for other sections.
        </p>
      ) : null}

      {shouldShowPrecautionWarning(sectionKind) ? (
        <p className="ptw-doc-warning">{PRECAUTION_WARNING}</p>
      ) : null}

      {sectionKind !== SECTION_KIND.GENERAL && !useAuditLayout && !useRiskLayout ? (
        <div className="ptw-doc-section-title">{title}</div>
      ) : null}

      {sectionSkipable ? (
        <div className="ptw-doc-risk-gateway">
          <p className="ptw-doc-risk-gateway__lead">
            {isRiskSection
              ? "Can this risk assessment section be skipped for this permit?"
              : "Can this section be skipped for this permit?"}
          </p>
          <div className="ptw-doc-inline-yesno">
            <label className="ptw-doc-inline-yesno__opt">
              <input
                type="radio"
                name="ptw-doc-skip-choice"
                value="yes"
                checked={skipChoice === "yes"}
                onChange={() => setSkipChoice("yes")}
              />
              <span>Yes — skip this section</span>
            </label>
            <label className="ptw-doc-inline-yesno__opt">
              <input
                type="radio"
                name="ptw-doc-skip-choice"
                value="no"
                checked={skipChoice === "no"}
                onChange={() => setSkipChoice("no")}
              />
              <span>No — complete section</span>
            </label>
          </div>
          {skipChoice === "yes" ? (
            <table className="ptw-doc-job-table ptw-doc-job-table--compact">
              <tbody>
                <tr>
                  <td className="ptw-doc-job-table__label">Reference (optional)</td>
                  <td colSpan={3}>
                    <input
                      className="ptw-doc-input"
                      value={skipReference}
                      onChange={(e) => setSkipReference(e.target.value)}
                    />
                  </td>
                </tr>
                <tr>
                  <td className="ptw-doc-job-table__label">Notes (optional)</td>
                  <td colSpan={3}>
                    <textarea
                      className="ptw-doc-input ptw-doc-input--area"
                      rows={2}
                      value={skipNotes}
                      onChange={(e) => setSkipNotes(e.target.value)}
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          ) : null}
        </div>
      ) : null}

      {auditTable}
      {riskTable}
      {questionTable}
    </div>
  );
}
