import React from "react";
import AuthenticatedMedia from "../common/AuthenticatedMedia.jsx";
import {
  getQuestionOptionLabels,
  getSignoffRoleLabel,
  isAuthorizationQuestionType,
  isDeclarationTextQuestion,
  isFillableTextQuestion,
  isImageQuestionType,
  OPTIONS_DISPLAY_MODE,
  parseSignoffAnswer,
  QUESTION_TYPE_KIND,
  resolveOptionsDisplayMode,
  resolveQuestionTypeKind
} from "../../utils/questionTypeHelpers.js";
import { usesTriStateColumns } from "./PtwDocumentQuestionsTable.jsx";

function typeOptionsForQuestion(question, questionTypeOptions) {
  if (question?.question_type) {
    return [
      {
        value: String(question.question_type_id ?? ""),
        label: question.question_type
      }
    ];
  }
  return questionTypeOptions;
}

function PreviewValue({ value, emptyLabel = "—" }) {
  const text = String(value ?? "").trim();
  return (
    <div className="ptw-preview-value">{text || emptyLabel}</div>
  );
}

function PreviewMediaList({ items = [], alt = "Attachment" }) {
  if (!items.length) return <PreviewValue emptyLabel="—" />;
  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="ptw-preview-media ptw-preview-media--video"
          preferredKind={item.preferredKind}
        />
      ))}
    </div>
  );
}

function PreviewChecklistCell({ selected, option }) {
  return (
    <td className="ptw-doc-check-cell-wrap">
      <div
        className={`ptw-doc-check-cell ptw-doc-check-cell--readonly${
          selected ? " ptw-doc-check-cell--selected" : ""
        }`}
        aria-label={option}
      >
        {selected ? (
          <span className="ptw-doc-check-cell__mark" aria-hidden="true">
            ✓
          </span>
        ) : null}
        <span className="ptw-doc-check-cell__label">{option}</span>
      </div>
    </td>
  );
}

function PreviewQuestionField({
  question,
  questionTypeOptions,
  value,
  mediaItems = []
}) {
  const typeOpts = typeOptionsForQuestion(question, questionTypeOptions);
  const typeId = question.question_type_id;
  const kind = resolveQuestionTypeKind(typeId, typeOpts, question.question_type);
  const displayMode = resolveOptionsDisplayMode(typeId, typeOpts, question.question_type);
  const optionLabels = getQuestionOptionLabels(question);
  const showMedia =
    Boolean(question.allows_media) ||
    isImageQuestionType(typeId, typeOpts) ||
    kind === QUESTION_TYPE_KIND.IMAGE;

  if (kind === QUESTION_TYPE_KIND.YES_NO) {
    return <span className="ptw-doc-muted">See checklist columns →</span>;
  }

  if (kind === QUESTION_TYPE_KIND.IMAGE || (showMedia && !String(value).trim())) {
    return <PreviewMediaList items={mediaItems} alt={question.question} />;
  }

  if (kind === QUESTION_TYPE_KIND.OPTIONS) {
    const isMulti = displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN;
    if (isMulti) {
      const selected = String(value || "")
        .split(",")
        .map((part) => part.trim())
        .filter(Boolean);
      return (
        <PreviewValue value={selected.length ? selected.join(", ") : ""} />
      );
    }
    return <PreviewValue value={value} />;
  }

  return (
    <div className="ptw-preview-answer-stack">
      <PreviewValue value={value} />
      {showMedia && mediaItems.length ? (
        <PreviewMediaList items={mediaItems} alt={question.question} />
      ) : null}
    </div>
  );
}

function PreviewSignoffTable({ declarations, rows, answers, mediaByQuestion }) {
  if (!declarations.length && !rows.length) return null;

  return (
    <div className="ptw-signoff-block">
      {declarations.map((question) => (
        <p key={question.question_id} className="ptw-signoff-block__declaration">
          {question.question}
        </p>
      ))}

      {rows.length ? (
        <div className="ptw-signoff-block__sheet">
          <table className="ptw-signoff-block__table">
            <colgroup>
              <col className="ptw-signoff-block__col-role" />
              <col className="ptw-signoff-block__col-name" />
              <col className="ptw-signoff-block__col-company" />
              <col className="ptw-signoff-block__col-signature" />
            </colgroup>
            <thead>
              <tr>
                <th className="ptw-signoff-block__col-role" scope="col" />
                <th className="ptw-signoff-block__col-name" scope="col">
                  NAME
                </th>
                <th className="ptw-signoff-block__col-company" scope="col">
                  COMPANY
                </th>
                <th className="ptw-signoff-block__col-signature" scope="col">
                  SIGNATURE
                </th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => {
                const qid = row.question_id;
                const data = parseSignoffAnswer(
                  answers[qid] ?? answers[String(qid)] ?? ""
                );
                const mediaItems =
                  mediaByQuestion[qid] || mediaByQuestion[String(qid)] || [];

                return (
                  <tr key={qid}>
                    <th scope="row" className="ptw-signoff-block__role-label">
                      {row.roleLabel}
                    </th>
                    <td className="ptw-signoff-block__name-cell">
                      <PreviewValue value={data.name} />
                    </td>
                    <td className="ptw-signoff-block__company-cell">
                      <PreviewValue value={data.company} />
                    </td>
                    <td className="ptw-signoff-block__signature-cell">
                      <PreviewMediaList items={mediaItems} alt={`${row.roleLabel} signature`} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}

export default function PtwDocumentQuestionsTablePreview({
  questions = [],
  questionTypeOptions,
  answers,
  mediaByQuestion = {},
  showHeader = true,
  showNumber = true,
  heading = "PLEASE ANSWER THE FOLLOWING QUESTIONS TRUTHFULLY, IF IN DOUBT, CONSULT YOUR MANAGER FOR ASSISTANCE."
}) {
  if (!questions.length) return null;

  const signoffQuestions = questions.filter((q) =>
    isAuthorizationQuestionType(q.question_type_id, typeOptionsForQuestion(q, questionTypeOptions), q.question_type)
  );
  const declarationQuestions = questions.filter((q) =>
    isDeclarationTextQuestion(q, questionTypeOptions)
  );
  const remaining = questions.filter(
    (q) =>
      !isAuthorizationQuestionType(
        q.question_type_id,
        typeOptionsForQuestion(q, questionTypeOptions),
        q.question_type
      ) && !isDeclarationTextQuestion(q, questionTypeOptions)
  );
  const textAnswerQuestions = remaining.filter((q) =>
    isFillableTextQuestion(q, questionTypeOptions)
  );
  const checklistQuestions = remaining.filter(
    (q) => !isFillableTextQuestion(q, questionTypeOptions)
  );
  const triState = checklistQuestions.filter((q) =>
    usesTriStateColumns(q, questionTypeOptions)
  );
  const freeText = checklistQuestions.filter(
    (q) => !usesTriStateColumns(q, questionTypeOptions)
  );

  const signoffRows = signoffQuestions.map((question) => ({
    question_id: question.question_id,
    roleLabel: getSignoffRoleLabel(question)
  }));

  const signoffBlock =
    signoffQuestions.length || declarationQuestions.length ? (
      <PreviewSignoffTable
        declarations={declarationQuestions}
        rows={signoffRows}
        answers={answers}
        mediaByQuestion={mediaByQuestion}
      />
    ) : null;

  const textAnswersBlock = textAnswerQuestions.length ? (
    showNumber ? (
      <div className="ptw-text-answers-block">
        {triState.length || freeText.length ? (
          <p className="ptw-text-answers-block__heading">Please provide the following information.</p>
        ) : (
          <p className="ptw-text-answers-block__heading">Submitted answers</p>
        )}
        <div className="ptw-text-answers-block__list">
          {textAnswerQuestions.map((question, index) => {
            const qid = question.question_id;
            const label = `${index + 1}. ${question.question}`;
            return (
              <div key={qid} className="ptw-text-answers-block__item ptw-text-answers-block__item--preview">
                <span className="ptw-text-answers-block__label">{label}</span>
                <PreviewValue value={answers[qid] ?? answers[String(qid)] ?? ""} />
              </div>
            );
          })}
        </div>
      </div>
    ) : (
      <table className="ptw-doc-job-table ptw-doc-job-table--general">
        <tbody>
          {textAnswerQuestions.map((question) => {
            const qid = question.question_id;
            const prompt = String(question.question || "").trim();
            const value = answers[qid] ?? answers[String(qid)] ?? "";
            const workInfo =
              prompt &&
              !prompt.endsWith(":") &&
              (prompt.length > 72 || /yes\s*\/\s*no/i.test(prompt));

            if (workInfo) {
              return (
                <React.Fragment key={qid}>
                  <tr>
                    <td colSpan={2} className="ptw-doc-job-table__work-info">
                      {prompt}
                    </td>
                  </tr>
                  <tr>
                    <td colSpan={2}>
                      <PreviewValue value={value} />
                    </td>
                  </tr>
                </React.Fragment>
              );
            }

            return (
              <tr key={qid}>
                <td className="ptw-doc-job-table__label">{prompt}</td>
                <td>
                  <PreviewValue value={value} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    )
  ) : null;

  const checklistTable =
    triState.length || freeText.length ? (
      <div className="ptw-doc-question-table-wrap">
        <table className="ptw-doc-question-table">
          <colgroup>
            <col className="ptw-doc-question-table__col-question" />
            <col className="ptw-doc-question-table__col-opt" />
            <col className="ptw-doc-question-table__col-opt" />
            <col className="ptw-doc-question-table__col-opt" />
          </colgroup>
          {triState.length ? (
            <thead>
              <tr>
                <th className="ptw-doc-question-table__heading">
                  {showHeader ? heading : "\u00A0"}
                </th>
                <th>Yes</th>
                <th>No</th>
                <th>N/a</th>
              </tr>
            </thead>
          ) : null}
          <tbody>
            {freeText.map((question, idx) => {
              const qid = question.question_id;
              const label = showNumber
                ? `${idx + 1} — ${question.question}`
                : question.question;
              const mediaItems =
                mediaByQuestion[qid] || mediaByQuestion[String(qid)] || [];
              return (
                <tr key={qid}>
                  <td className="ptw-doc-question-table__question">{label}</td>
                  <td className="ptw-doc-question-table__answer" colSpan={3}>
                    <PreviewQuestionField
                      question={question}
                      questionTypeOptions={questionTypeOptions}
                      value={answers[qid] ?? answers[String(qid)] ?? ""}
                      mediaItems={mediaItems}
                    />
                  </td>
                </tr>
              );
            })}
            {triState.map((question, idx) => {
              const qid = question.question_id;
              const label = showNumber
                ? `${freeText.length + idx + 1} — ${question.question}`
                : question.question;
              const value = answers[qid] ?? answers[String(qid)] ?? "";
              const isNoAnswer = String(value).trim().toLowerCase() === "no";
              return (
                <tr
                  key={qid}
                  className={isNoAnswer ? "ptw-doc-question-table__row--no" : undefined}
                >
                  <td
                    className={`ptw-doc-question-table__question${
                      isNoAnswer ? " ptw-doc-question-table__question--no" : ""
                    }`}
                  >
                    {label}
                  </td>
                  <PreviewChecklistCell selected={value === "Yes"} option="Yes" />
                  <PreviewChecklistCell selected={value === "No"} option="No" />
                  <PreviewChecklistCell selected={value === "N/a"} option="N/a" />
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    ) : null;

  if (!signoffBlock && !textAnswersBlock && !checklistTable) return null;

  return (
    <>
      {signoffBlock}
      {textAnswersBlock}
      {checklistTable}
    </>
  );
}
