import React from "react";
import AuthenticatedMedia from "../common/AuthenticatedMedia.jsx";
import PtwDocumentQuestionsTablePreview from "./PtwDocumentQuestionsTablePreview.jsx";
import PtwAuditSectionTablePreview from "./PtwAuditSectionTablePreview.jsx";
import PtwRiskAssessmentTablePreview from "./PtwRiskAssessmentTablePreview.jsx";
import { SECTION_KIND } from "../../utils/sectionTypeHelpers.js";
import { shouldUseAuditSectionLayout, auditSectionDisplayTitle } from "../../utils/auditSectionHelpers.js";
import {
  shouldUseRiskAssessmentSectionLayout,
  riskAssessmentSectionDisplayTitle
} from "../../utils/riskAssessmentHelpers.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 !";

function formatSectionTitle(title) {
  const raw = String(title || "").trim();
  return raw ? raw.toUpperCase() : "SECTION";
}

function resolvePreviewSectionTitle(section, useAuditLayout, useRiskLayout) {
  if (String(section?.title || "").trim()) {
    return formatSectionTitle(section.title);
  }
  if (useAuditLayout) return formatSectionTitle(auditSectionDisplayTitle(section));
  if (useRiskLayout) return formatSectionTitle(riskAssessmentSectionDisplayTitle(section));
  return formatSectionTitle("");
}

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

function PreviewMediaList({ items = [], alt = "Attachment", videoClassName = "" }) {
  if (!items.length) return null;
  return (
    <div className="ptw-preview-media-list">
      {items.map((item) => (
        <AuthenticatedMedia
          key={`${item.answersId}-${item.occurrence}`}
          url={item.url}
          answersId={item.answersId}
          occurrence={item.occurrence}
          alt={alt}
          className="ptw-preview-media"
          videoClassName={videoClassName || "ptw-preview-media ptw-preview-media--video"}
          preferredKind={item.preferredKind}
        />
      ))}
    </div>
  );
}

function PreviewSectionMedia({ sectionMedia }) {
  const videoItems = sectionMedia?.video || [];
  if (!videoItems.length) return null;

  return (
    <div className="ptw-doc-media-row ptw-doc-media-row--preview ptw-print-exclude">
      <span className="ptw-preview-media-label">Permit video</span>
      <PreviewMediaList
        items={videoItems.map((item) => ({ ...item, preferredKind: "video" }))}
        alt="Permit video"
        videoClassName="ptw-preview-media ptw-preview-media--video ptw-preview-media--section-video"
      />
    </div>
  );
}

export default function PtwDocumentSectionPreview({
  section,
  sectionKind,
  questions = [],
  questionTypeOptions,
  answers,
  mediaByQuestion = {},
  sectionMedia = null,
  skipped = false,
  formMeta = null,
  formTypes = []
}) {
  const useAuditLayout = shouldUseAuditSectionLayout(section, formMeta, formTypes);
  const useRiskLayout =
    !useAuditLayout && shouldUseRiskAssessmentSectionLayout(section, questions);
  const title = resolvePreviewSectionTitle(section, useAuditLayout, useRiskLayout);
  const showChecklistHeader = sectionKind !== SECTION_KIND.GENERAL;
  const showQuestionNumbers = sectionKind !== SECTION_KIND.GENERAL;

  if (skipped) {
    const skipText =
      questions
        .map((q) => answers[q.question_id] ?? answers[String(q.question_id)] ?? "")
        .find((value) => String(value).trim()) || "This section was skipped.";

    return (
      <div className="ptw-doc-section ptw-doc-section--preview">
        <div className="ptw-doc-section-title">{title}</div>
        <div className="ptw-preview-skip-banner">
          <strong>Section skipped</strong>
          <p>{skipText}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="ptw-doc-section ptw-doc-section--preview">
      <PreviewSectionMedia sectionMedia={sectionMedia} />

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

      <div className="ptw-doc-section-title">{title}</div>

      {useAuditLayout && questions.length ? (
        <PtwAuditSectionTablePreview
          section={section}
          questions={questions}
          answers={answers}
        />
      ) : useRiskLayout && questions.length ? (
        <PtwRiskAssessmentTablePreview
          section={section}
          questions={questions}
          answers={answers}
        />
      ) : questions.length ? (
        <PtwDocumentQuestionsTablePreview
          questions={questions}
          questionTypeOptions={questionTypeOptions}
          answers={answers}
          mediaByQuestion={mediaByQuestion}
          showHeader={showChecklistHeader}
          showNumber={showQuestionNumbers}
        />
      ) : (
        <p className="ptw-preview-empty-section">No questions in this section.</p>
      )}
    </div>
  );
}
