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;
}

export default function QuestionAnswerField({
  question,
  questionTypeOptions = [],
  value = "",
  onChange,
  mediaFiles = [],
  onMediaChange
}) {
  const qid = question.question_id;
  const typeOpts = typeOptionsForQuestion(question, questionTypeOptions);
  const typeId = question.question_type_id;
  const kind = resolveQuestionTypeKind(typeId, typeOpts);
  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);

  if (kind === QUESTION_TYPE_KIND.TEXT) {
    return (
      <div className="ptw-fill-answer">
        <textarea
          className="ptw-mgmt-input ptw-mgmt-textarea"
          rows={3}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="Enter your answer"
        />
        {showMedia ? (
          <FileUploadField
            label="Attach image or video (optional)"
            multiple
            accept="image/*,video/*"
            onChange={(files) => onMediaChange?.(qid, files || [])}
          />
        ) : null}
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.NUMBER) {
    return (
      <div className="ptw-fill-answer">
        <input
          type="number"
          className="ptw-mgmt-input"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="Enter a number"
        />
        {showMedia ? (
          <FileUploadField
            label="Attach image or video (optional)"
            multiple
            accept="image/*,video/*"
            onChange={(files) => onMediaChange?.(qid, files || [])}
          />
        ) : null}
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.YES_NO) {
    return (
      <div className="ptw-fill-answer ptw-fill-answer--yesno">
        {["Yes", "No"].map((opt) => (
          <label key={opt} className="ptw-mgmt-type-format__radio">
            <input
              type="radio"
              name={`q-${qid}`}
              value={opt}
              checked={value === opt}
              onChange={() => setValue(opt)}
            />
            <span>{opt}</span>
          </label>
        ))}
        {showMedia ? (
          <FileUploadField
            label="Attach image or video (optional)"
            multiple
            accept="image/*,video/*"
            onChange={(files) => onMediaChange?.(qid, files || [])}
          />
        ) : null}
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.IMAGE) {
    return (
      <div className="ptw-fill-answer">
        <p className="ptw-muted ptw-fill-answer__note">
          Attach one or more images. You can mark or draw on them after upload when supported.
        </p>
        <FileUploadField
          label="Upload image(s)"
          multiple
          accept="image/*"
          onChange={(files) => onMediaChange?.(qid, files || [])}
        />
        {mediaFiles?.length ? (
          <p className="ptw-muted">{mediaFiles.length} file(s) selected</p>
        ) : null}
      </div>
    );
  }

  if (kind === QUESTION_TYPE_KIND.OPTIONS) {
    if (displayMode === OPTIONS_DISPLAY_MODE.MCQ_RADIO) {
      return (
        <div className="ptw-fill-answer ptw-fill-answer--options">
          {optionLabels.length === 0 ? (
            <p className="ptw-muted">No options configured for this question.</p>
          ) : (
            optionLabels.map((opt) => (
              <label key={opt} className="ptw-mgmt-type-format__radio">
                <input
                  type="radio"
                  name={`q-${qid}`}
                  value={opt}
                  checked={value === opt}
                  onChange={() => setValue(opt)}
                />
                <span>{opt}</span>
              </label>
            ))
          )}
          {showMedia ? (
            <FileUploadField
              label="Attach image or video (optional)"
              multiple
              accept="image/*,video/*"
              onChange={(files) => onMediaChange?.(qid, files || [])}
            />
          ) : null}
        </div>
      );
    }

    if (displayMode === OPTIONS_DISPLAY_MODE.MMCQ_CHECKBOX) {
      const selected = String(value || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
      const toggle = (opt) => {
        const has = selected.includes(opt);
        const next = has ? selected.filter((o) => o !== opt) : [...selected, opt];
        setValue(next.join(", "));
      };
      return (
        <div className="ptw-fill-answer ptw-fill-answer--options">
          {optionLabels.length === 0 ? (
            <p className="ptw-muted">No options configured for this question.</p>
          ) : (
            optionLabels.map((opt) => (
              <label key={opt} className="ptw-mgmt-type-format__radio">
                <input
                  type="checkbox"
                  checked={selected.includes(opt)}
                  onChange={() => toggle(opt)}
                />
                <span>{opt}</span>
              </label>
            ))
          )}
          {showMedia ? (
            <FileUploadField
              label="Attach image or video (optional)"
              multiple
              accept="image/*,video/*"
              onChange={(files) => onMediaChange?.(qid, files || [])}
            />
          ) : null}
        </div>
      );
    }

    if (displayMode === OPTIONS_DISPLAY_MODE.MULTI_DROPDOWN) {
      const selected = String(value || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
      return (
        <div className="ptw-fill-answer">
          <select
            className="ptw-mgmt-input ptw-mgmt-select"
            multiple
            value={selected}
            onChange={(e) => {
              const next = Array.from(e.target.selectedOptions).map((o) => o.value);
              setValue(next.join(", "));
            }}
            size={Math.min(Math.max(optionLabels.length, 3), 8)}
          >
            {optionLabels.map((opt) => (
              <option key={opt} value={opt}>
                {opt}
              </option>
            ))}
          </select>
          <p className="ptw-muted ptw-fill-answer__note">Hold Ctrl (Windows) or Cmd (Mac) to select multiple.</p>
          {showMedia ? (
            <FileUploadField
              label="Attach image or video (optional)"
              multiple
              accept="image/*,video/*"
              onChange={(files) => onMediaChange?.(qid, files || [])}
            />
          ) : null}
        </div>
      );
    }

    if (displayMode === OPTIONS_DISPLAY_MODE.SINGLE_DROPDOWN) {
      return (
        <div className="ptw-fill-answer">
          <select
            className="ptw-mgmt-input ptw-mgmt-select"
            value={value}
            onChange={(e) => setValue(e.target.value)}
          >
            <option value="">Select an option</option>
            {optionLabels.map((opt) => (
              <option key={opt} value={opt}>
                {opt}
              </option>
            ))}
          </select>
          {showMedia ? (
            <FileUploadField
              label="Attach image or video (optional)"
              multiple
              accept="image/*,video/*"
              onChange={(files) => onMediaChange?.(qid, files || [])}
            />
          ) : null}
        </div>
      );
    }

    return (
      <div className="ptw-fill-answer">
        <input
          type="text"
          className="ptw-mgmt-input"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="Enter your answer"
        />
      </div>
    );
  }

  return (
    <div className="ptw-fill-answer">
      <input
        type="text"
        className="ptw-mgmt-input"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Enter your answer"
      />
    </div>
  );
}
