import React from "react";
import { useNavigate } from "react-router-dom";
import Button from "../../../common/Button";
import "../../user-management/styles/UserCreateForm.css";

const QuestionForm = ({
  formData,
  questionTypes,
  loading,
  error,
  onSubmit,
  onInputChange,
  onOptionsChange,
  onClearForm,
}) => {
  const navigate = useNavigate();
  const isEditMode = formData.id !== null && formData.id !== undefined;

  const questionTypeNeedsOptions = (questionTypeId) => {
    if (!questionTypeId) return false;
    const idNum = parseInt(questionTypeId, 10);
    if (!Number.isNaN(idNum) && (idNum === 4 || idNum === 5)) {
      return true;
    }
    const type = questionTypes.find(
      (t) => String(t.question_type_id) === String(questionTypeId)
    );
    if (!type) return false;
    const name = (type.type_name || type.name || type.question_type || "").toLowerCase();
    return (
      name.includes("dropdown") ||
      name.includes("choice") ||
      name.includes("mmcq")
    );
  };

  const needsOptions = questionTypeNeedsOptions(formData.question_type_id);
  const optionsList = Array.isArray(formData.options) ? formData.options : [];

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

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

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

  return (
    <div className="tab-content active" id="createTab">
      <div className="form-section">
        <div className="form-header">
          <h1 className="user-create-form-header-title">
            {isEditMode ? "Question Update" : "Question Create"}
          </h1>
        </div>

        <form className="user-form" onSubmit={onSubmit}>
          {error && <div className="user-create-error">{error}</div>}
          <div className="form-grid">
            <div className="form-column">
              <div className="input-group">
                <label htmlFor="question" className="input-label">
                  Question Text <span className="required-asterisk">*</span>
                </label>
                <input
                  type="text"
                  id="question"
                  name="question"
                  className="input-field"
                  placeholder="Enter question text"
                  value={formData.question}
                  onChange={onInputChange}
                  required
                />
              </div>
            </div>
            <div className="form-column">
              <div className="input-group">
                <label htmlFor="question_type_id" className="input-label">
                  Question Type <span className="required-asterisk">*</span>
                </label>
                <select
                  id="question_type_id"
                  name="question_type_id"
                  className="input-field select-field"
                  value={formData.question_type_id}
                  onChange={onInputChange}
                  required
                >
                  <option value="">Select Question Type</option>
                  {questionTypes.map((type) => (
                    <option key={type.question_type_id} value={type.question_type_id}>
                      {type.type_name || type.name || type.question_type || `Type ${type.question_type_id}`}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>
          {needsOptions && (
            <div className="form-grid">
              <div className="form-column form-column-full">
                <div className="input-group options-builder">
                  <label className="input-label">
                    Options <span className="required-asterisk">*</span>
                  </label>
                  <span className="input-hint">Add each choice as a separate option. Users will see these as single selection dropdown or multiple dropdown choices.</span>
                  <div className="options-list">
                    {optionsList.map((opt, index) => (
                      <div key={index} className="option-row">
                        <span className="option-number">{index + 1}.</span>
                        <input
                          type="text"
                          className="input-field option-input"
                          placeholder={`Option ${index + 1}`}
                          value={opt}
                          onChange={(e) => handleOptionChange(index, e.target.value)}
                        />
                        <button
                          type="button"
                          className="option-remove-btn"
                          onClick={() => handleRemoveOption(index)}
                          title="Remove option"
                          aria-label="Remove option"
                        >
                          <svg viewBox="0 0 24 24" fill="none" width="18" height="18">
                            <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </button>
                      </div>
                    ))}
                  </div>
                  <button
                    type="button"
                    className="option-add-btn"
                    onClick={handleAddOption}
                  >
                    <svg viewBox="0 0 24 24" fill="none" width="18" height="18">
                      <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    Add option
                  </button>
                  {optionsList.length === 0 && (
                    <p className="options-empty-msg">No options yet. Click &quot;Add option&quot; to add choices.</p>
                  )}
                </div>
              </div>
            </div>
          )}
          <div className="form-grid">
            <div className="form-column">
              <div className="input-group">
                <label className="input-label">
                  <input
                    type="checkbox"
                    name="allows_media"
                    checked={formData.allows_media}
                    onChange={onInputChange}
                    style={{ marginRight: "0.5rem" }}
                  />
                  Allows Media Attachments?
                </label>
              </div>
            </div>
          </div>
          <div className="form-actions">
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                onClearForm();
                if (isEditMode) {
                  navigate("/questions");
                }
              }}
              disabled={loading}
            >
              {isEditMode ? "Cancel" : "Clear Form"}
            </Button>
            <Button type="submit" variant="primary" disabled={loading}>
              {loading
                ? isEditMode
                  ? "Updating..."
                  : "Saving..."
                : isEditMode
                ? "Update Question"
                : "Submit"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default QuestionForm;
