import React from "react";
import {
  OPTIONS_DISPLAY_MODE,
  QUESTION_TYPE_KIND,
  getOptionsBuilderHint,
  normalizeOptionsArray,
  resolveOptionsDisplayMode
} from "../../../utils/questionTypeHelpers.js";
import { RISK_ASSESSMENT_COLUMN_HEADERS } from "../../../utils/riskAssessmentHelpers.js";

function OptionsAnswerPreview({ displayMode, optionLabels }) {
  if (!optionLabels.length) return null;

  const previewTitle =
    displayMode === OPTIONS_DISPLAY_MODE.MCQ_RADIO
      ? "Answer preview (radio — one selection)"
      : displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX
        ? "Answer preview (checkboxes — multiple selections)"
        : displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN
          ? "Answer preview (dropdown — multiple selections)"
          : displayMode === OPTIONS_DISPLAY_MODE.SINGLE_DROPDOWN
            ? "Answer preview (dropdown — one selection)"
            : "Answer preview";

  if (displayMode === OPTIONS_DISPLAY_MODE.MCQ_RADIO) {
    return (
      <div className="ptw-options-preview" aria-hidden>
        <p className="ptw-options-preview__title">{previewTitle}</p>
        <div className="ptw-options-preview__list">
          {optionLabels.map((label, index) => (
            <label key={index} className="ptw-mgmt-type-format__radio">
              <input type="radio" name="ptw-mcq-preview" disabled readOnly />
              <span>{label}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  if (displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX) {
    return (
      <div className="ptw-options-preview" aria-hidden>
        <p className="ptw-options-preview__title">{previewTitle}</p>
        <div className="ptw-options-preview__list">
          {optionLabels.map((label, index) => (
            <label key={index} className="ptw-mgmt-type-format__radio">
              <input type="checkbox" disabled readOnly />
              <span>{label}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  if (displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN) {
    return (
      <div className="ptw-options-preview" aria-hidden>
        <p className="ptw-options-preview__title">{previewTitle}</p>
        <select
          className="ptw-mgmt-input ptw-mgmt-select"
          multiple
          disabled
          size={Math.min(optionLabels.length, 5)}
        >
          {optionLabels.map((label, index) => (
            <option key={index} value={label}>
              {label}
            </option>
          ))}
        </select>
      </div>
    );
  }

  if (displayMode === OPTIONS_DISPLAY_MODE.SINGLE_DROPDOWN) {
    return (
      <div className="ptw-options-preview" aria-hidden>
        <p className="ptw-options-preview__title">{previewTitle}</p>
        <select className="ptw-mgmt-input ptw-mgmt-select" disabled defaultValue="">
          <option value="">Select an option</option>
          {optionLabels.map((label, index) => (
            <option key={index} value={label}>
              {label}
            </option>
          ))}
        </select>
      </div>
    );
  }

  return null;
}

function OptionsBuilder({ options, onOptionsChange, typeId, questionTypeOptions }) {
  const optionsList = Array.isArray(options) ? options : [];
  const displayMode = resolveOptionsDisplayMode(typeId, questionTypeOptions);
  const optionLabels = normalizeOptionsArray(optionsList);

  const handleAdd = () => {
    onOptionsChange?.([...optionsList, ""]);
  };

  const handleChange = (index, value) => {
    const updated = [...optionsList];
    updated[index] = value;
    onOptionsChange?.(updated);
  };

  const handleRemove = (index) => {
    onOptionsChange?.(optionsList.filter((_, i) => i !== index));
  };

  return (
    <div className="ptw-options-builder">
      <span className="ptw-mgmt-field__label">
        Options <em className="ptw-mgmt-required">*</em>
      </span>
      <p className="ptw-mgmt-type-format__hint">
        {getOptionsBuilderHint(typeId, questionTypeOptions)}
      </p>
      <div className="ptw-options-list">
        {optionsList.map((opt, index) => (
          <div key={index} className="ptw-option-row">
            <span className="ptw-option-number">{index + 1}.</span>
            <input
              type="text"
              className="ptw-mgmt-input ptw-option-input"
              placeholder={`Option ${index + 1}`}
              value={opt}
              onChange={(e) => handleChange(index, e.target.value)}
            />
            <button
              type="button"
              className="ptw-option-remove-btn"
              onClick={() => handleRemove(index)}
              title="Remove option"
              aria-label="Remove option"
            >
              ×
            </button>
          </div>
        ))}
      </div>
      <button type="button" className="ptw-option-add-btn" onClick={handleAdd}>
        + Add option
      </button>
      {optionsList.length === 0 ? (
        <p className="ptw-options-empty-msg">
          No options yet. Click &quot;Add option&quot; to add choices.
        </p>
      ) : null}
      <OptionsAnswerPreview displayMode={displayMode} optionLabels={optionLabels} />
    </div>
  );
}

function TypeFormatInfo({ title, children }) {
  return (
    <div className="ptw-mgmt-type-format">
      {title ? <p className="ptw-mgmt-type-format__title">{title}</p> : null}
      {children}
    </div>
  );
}

export default function QuestionTypeFormatPanel({
  kind,
  typeId,
  questionTypeOptions = [],
  options = [],
  onOptionsChange
}) {
  if (!kind) return null;

  switch (kind) {
    case QUESTION_TYPE_KIND.TEXT:
      return (
        <TypeFormatInfo title="Text answer format">
          <p className="ptw-mgmt-type-format__hint">
            Type 1 questions render as labelled text fields outside the Yes/No checklist table.
            Short prompts use a compact textarea; longer prompts expand automatically. Use 80+
            characters in the question text only when the copy is a declaration above a sign-off
            table (no answer required).
          </p>
          <div className="ptw-mgmt-type-format__preview" aria-hidden>
            <label className="ptw-mgmt-type-format__preview-label">
              Sample question
              <textarea
                className="ptw-mgmt-input ptw-mgmt-input--area"
                disabled
                rows={2}
                placeholder="Enter your answer"
              />
            </label>
          </div>
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.NUMBER:
      return (
        <TypeFormatInfo title="Number answer format">
          <p className="ptw-mgmt-type-format__hint">
            Respondents will enter a numeric value. No additional configuration is required.
          </p>
          <div className="ptw-mgmt-type-format__preview" aria-hidden>
            <input
              type="number"
              className="ptw-mgmt-input"
              disabled
              placeholder="0"
            />
          </div>
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.YES_NO:
      return (
        <TypeFormatInfo title="Yes / No answer format">
          <p className="ptw-mgmt-type-format__hint">
            Respondents choose Yes or No. Answers are stored as those labels; no custom options are saved.
          </p>
          <div className="ptw-mgmt-type-format__preview ptw-mgmt-type-format__yesno" aria-hidden>
            <label className="ptw-mgmt-type-format__radio">
              <input type="radio" disabled checked readOnly />
              <span>Yes</span>
            </label>
            <label className="ptw-mgmt-type-format__radio">
              <input type="radio" disabled readOnly />
              <span>No</span>
            </label>
          </div>
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.OPTIONS:
      return (
        <TypeFormatInfo>
          <OptionsBuilder
            options={options}
            onOptionsChange={onOptionsChange}
            typeId={typeId}
            questionTypeOptions={questionTypeOptions}
          />
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.IMAGE:
      return (
        <TypeFormatInfo title="Image mark / attach format">
          <p className="ptw-mgmt-type-format__hint">
            Respondents attach image(s) and can mark or draw on them after upload. Image/video upload is enabled for this question.
          </p>
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.AUTHORIZATION:
      return (
        <TypeFormatInfo title="Authorisation sign-off format">
          <p className="ptw-mgmt-type-format__hint">
            Each type 9 question becomes one row in the sign-off table (NAME, COMPANY, SIGNATURE).
            Use the first mapped option or question text as the row label (e.g. PERMIT ISSUER).
            Add separate TEXT questions (80+ characters) in the same section for declaration copy above the table.
          </p>
          <OptionsBuilder
            options={options}
            onOptionsChange={onOptionsChange}
            typeId={typeId}
            questionTypeOptions={questionTypeOptions}
          />
        </TypeFormatInfo>
      );

    case QUESTION_TYPE_KIND.RISK_ASSESSMENT:
      return (
        <TypeFormatInfo title="Risk assessment matrix format">
          <p className="ptw-mgmt-type-format__hint">
            Questions with this type render in the 5-column RISK ASSESSMENT table on permit forms.
            Map one question per cell using the column labels (STEPS, WHAT COULD GO WRONG?, etc.)
            repeated for each row, or map questions in row order (5 per row). Risk sections always
            use this table layout.
          </p>
          <div className="ptw-mgmt-type-format__preview ptw-risk-section ptw-risk-section--preview" aria-hidden>
            <table className="ptw-doc-job-table ptw-risk-section__table">
              <thead>
                <tr>
                  {RISK_ASSESSMENT_COLUMN_HEADERS.map((header) => (
                    <th key={header} className="ptw-doc-job-table__label ptw-risk-section__head">
                      {header}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <tr>
                  {RISK_ASSESSMENT_COLUMN_HEADERS.map((header) => (
                    <td key={header}>
                      <div className="ptw-preview-value">…</div>
                    </td>
                  ))}
                </tr>
              </tbody>
            </table>
          </div>
        </TypeFormatInfo>
      );

    default:
      return null;
  }
}
