import React from "react";
import {
  getSignoffRoleLabel,
  isAuthorizationQuestionType,
  isDeclarationTextQuestion,
  isFillableTextQuestion,
  QUESTION_TYPE_KIND,
  resolveQuestionTypeKind,
  serializeSignoffAnswer
} from "../../utils/questionTypeHelpers.js";
import PtwSignoffTable from "./PtwSignoffTable.jsx";
import PtwTextAnswersBlock from "./PtwTextAnswersBlock.jsx";
import PtwDocumentQuestionField, {
  PtwDocumentChecklistCell
} from "./PtwDocumentQuestionField.jsx";

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

export function usesTriStateColumns(question, questionTypeOptions) {
  const typeOpts = typeOptionsForQuestion(question, questionTypeOptions);
  const kind = resolveQuestionTypeKind(
    question.question_type_id,
    typeOpts,
    question.question_type
  );
  return kind === QUESTION_TYPE_KIND.YES_NO;
}

function isSignoffQuestion(question, questionTypeOptions) {
  const typeOpts = typeOptionsForQuestion(question, questionTypeOptions);
  return isAuthorizationQuestionType(
    question.question_type_id,
    typeOpts,
    question.question_type
  );
}

function ChecklistRow({
  question,
  index,
  questionTypeOptions,
  value,
  onChange,
  showNumber = true
}) {
  const qid = question.question_id;
  const label = showNumber ? `${index + 1} — ${question.question}` : question.question;
  const isNoAnswer = String(value || "").trim().toLowerCase() === "no";

  return (
    <tr 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>
      <PtwDocumentChecklistCell value={value} option="Yes" onChange={(opt) => onChange(qid, opt)} />
      <PtwDocumentChecklistCell value={value} option="No" onChange={(opt) => onChange(qid, opt)} />
      <PtwDocumentChecklistCell value={value} option="N/a" onChange={(opt) => onChange(qid, opt)} />
    </tr>
  );
}

function AnswerRow({
  question,
  index,
  questionTypeOptions,
  value,
  onChange,
  mediaByQuestion,
  onMediaChange,
  showNumber = true
}) {
  const label = showNumber ? `${index + 1} — ${question.question}` : question.question;

  return (
    <tr>
      <td className="ptw-doc-question-table__question">{label}</td>
      <td className="ptw-doc-question-table__answer" colSpan={3}>
        <PtwDocumentQuestionField
          question={question}
          questionTypeOptions={questionTypeOptions}
          value={value}
          onChange={onChange}
          mediaFiles={mediaByQuestion[question.question_id]}
          onMediaChange={onMediaChange}
          variant="job"
        />
      </td>
    </tr>
  );
}

export default function PtwDocumentQuestionsTable({
  questions = [],
  questionTypeOptions,
  answers,
  onChange,
  mediaByQuestion,
  onMediaChange,
  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) => isSignoffQuestion(q, questionTypeOptions));
  const declarationQuestions = questions.filter((q) =>
    isDeclarationTextQuestion(q, questionTypeOptions)
  );
  const remaining = questions.filter(
    (q) =>
      !isSignoffQuestion(q, questionTypeOptions) &&
      !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)
  }));

  function handleSignoffAnswerChange(questionId, data) {
    onChange?.(questionId, serializeSignoffAnswer(data));
  }

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

  const textAnswersBlock = textAnswerQuestions.length ? (
    <PtwTextAnswersBlock
      questions={textAnswerQuestions}
      answers={answers}
      onChange={onChange}
      showNumber={showNumber}
      variant={showNumber ? "default" : "job"}
      heading={
        showNumber
          ? triState.length || freeText.length
            ? "Please provide the following information."
            : "Please enter your answers below."
          : ""
      }
    />
  ) : 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((q, idx) => (
              <AnswerRow
                key={q.question_id}
                question={q}
                index={idx}
                questionTypeOptions={questionTypeOptions}
                value={answers[q.question_id] ?? ""}
                onChange={onChange}
                mediaByQuestion={mediaByQuestion}
                onMediaChange={onMediaChange}
                showNumber={showNumber}
              />
            ))}
            {triState.map((q, idx) => (
              <ChecklistRow
                key={q.question_id}
                question={q}
                index={freeText.length + idx}
                questionTypeOptions={questionTypeOptions}
                value={answers[q.question_id] ?? ""}
                onChange={onChange}
                showNumber={showNumber}
              />
            ))}
          </tbody>
        </table>
      </div>
    ) : null;

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

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