import React from "react";
import FileUploadField from "../common/FileUploadField.jsx";
import {
  OPTIONS_DISPLAY_MODE,
  QUESTION_TYPE_KIND,
  getQuestionOptionLabels,
  isImageQuestionType,
  resolveOptionsDisplayMode,
  resolveQuestionTypeKind
} from "../../utils/questionTypeHelpers.js";

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

function DocTextInput({ value, onChange, multiline = false }) {
  if (multiline) {
    return (
      <textarea
        className="ptw-doc-input ptw-doc-input--area"
        rows={2}
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
    );
  }
  return (
    <input
      type="text"
      className="ptw-doc-input"
      value={value}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

function ChecklistMarkIcon({ option }) {
  if (option === "Yes") {
    return (
      <svg
        className="ptw-doc-check-cell__mark ptw-doc-check-cell__mark--yes"
        viewBox="0 0 16 16"
        aria-hidden="true"
      >
        <path
          d="M3 8.5L6.5 12L13 4"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    );
  }
  if (option === "No") {
    return (
      <svg
        className="ptw-doc-check-cell__mark ptw-doc-check-cell__mark--no"
        viewBox="0 0 16 16"
        aria-hidden="true"
      >
        <path
          d="M4 4L12 12M12 4L4 12"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
        />
      </svg>
    );
  }
  return (
    <svg
      className="ptw-doc-check-cell__mark ptw-doc-check-cell__mark--na"
      viewBox="0 0 16 16"
      aria-hidden="true"
    >
      <path
        d="M3 8.5L6.5 12L13 4"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function PtwDocumentChecklistCell({ value, option, onChange }) {
  const selected = value === option;

  return (
    <td className="ptw-doc-check-cell-wrap">
      <button
        type="button"
        className={`ptw-doc-check-cell${selected ? " ptw-doc-check-cell--selected" : ""}`}
        aria-pressed={selected}
        aria-label={option}
        onClick={() => onChange(option)}
      >
        {selected ? <ChecklistMarkIcon option={option} /> : null}
        <span className="ptw-doc-check-cell__label">{option}</span>
      </button>
    </td>
  );
}

export default function PtwDocumentQuestionField({
  question,
  questionTypeOptions = [],
  sectionQuestions = [],
  value = "",
  onChange,
  mediaFiles = [],
  onMediaChange,
  variant = "table"
}) {
  const qid = question.question_id;
  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;

  const setValue = (next) => onChange?.(qid, next);
  const radioName = `ptw-doc-q-${qid}`;

  if (kind === QUESTION_TYPE_KIND.TEXT) {
    const multiline = String(question.question || "").length > 80;
    return (
      <div className="ptw-doc-answer-stack">
        <DocTextInput value={value} onChange={setValue} multiline={multiline} />
        {showMedia ? (
          <FileUploadField
            label="Attach file (optional)"
            multiple
            accept="image/*,video/*"
            onChange={(files) => onMediaChange?.(qid, files || [])}
          />
        ) : null}
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.NUMBER) {
    return (
      <input
        type="number"
        className="ptw-doc-input"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
    );
  }

  if (kind === QUESTION_TYPE_KIND.YES_NO) {
    return (
      <div className="ptw-doc-inline-yesno ptw-doc-inline-yesno--fallback">
        <span className="ptw-doc-muted">Use Yes / No / N/a columns →</span>
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.IMAGE) {
    return (
      <FileUploadField
        label="Upload image(s)"
        multiple
        accept="image/*"
        onChange={(files) => onMediaChange?.(qid, files || [])}
      />
    );
  }

  if (kind === QUESTION_TYPE_KIND.OPTIONS) {
    if (
      displayMode === OPTIONS_DISPLAY_MODE.SINGLE_DROPDOWN ||
      displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN
    ) {
      const isMulti = displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN;
      const selected = String(value || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
      return (
        <select
          className="ptw-doc-input ptw-doc-input--select"
          multiple={isMulti}
          value={isMulti ? selected : value}
          onChange={(e) => {
            if (isMulti) {
              const next = Array.from(e.target.selectedOptions).map((o) => o.value);
              setValue(next.join(", "));
            } else {
              setValue(e.target.value);
            }
          }}
        >
          {!isMulti ? <option value="">Select…</option> : null}
          {optionLabels.map((opt) => (
            <option key={opt} value={opt}>
              {opt}
            </option>
          ))}
        </select>
      );
    }

    return (
      <div className="ptw-doc-inline-yesno">
        {optionLabels.map((opt) => (
          <label key={opt} className="ptw-doc-inline-yesno__opt">
            <input
              type={displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX ? "checkbox" : "radio"}
              name={radioName}
              checked={
                displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX
                  ? String(value || "")
                      .split(",")
                      .map((s) => s.trim())
                      .includes(opt)
                  : value === opt
              }
              onChange={() => {
                if (displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX) {
                  const selected = String(value || "")
                    .split(",")
                    .map((s) => s.trim())
                    .filter(Boolean);
                  const has = selected.includes(opt);
                  setValue(has ? selected.filter((o) => o !== opt).join(", ") : [...selected, opt].join(", "));
                } else {
                  setValue(opt);
                }
              }}
            />
            <span>{opt}</span>
          </label>
        ))}
      </div>
    );
  }

  return (
    <input
      type="text"
      className="ptw-doc-input"
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

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