import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  createOracQuestion,
  createOracQuestionOption,
  deleteOracQuestion,
  deleteOracQuestionOption,
  fetchOracQuestionOptionsByQuestionId,
  fetchOracQuestionsList,
  fetchOracQuestionTypes
} from '../../api.js';
import './admin-shared.css';
import './AdminFormBuilderPage.css';

/** Matches DB labels like "multiple dropdown", "Dropdown", "multi-select". */
function isDropdownQuestionType(label) {
  if (!label || typeof label !== 'string') return false;
  const s = label.toLowerCase().trim();
  return /(dropdown|drop-down|drop down|select\s*list|multi-select|multiple\s*select)/.test(s);
}

const MODE_COPY = {
  list: {
    title: 'Question list',
    lead: 'Browse all questions. For dropdown types, use Options to edit choices. Delete removes a question from the bank.'
  },
  add: {
    title: 'Add question',
    lead: 'Create a new question and choose its type. For dropdown types, add answer options before saving.'
  }
};

/** @param {'list' | 'add'} mode */
function AdminQuestionsPage({ mode = 'list' }) {
  const [questionTypes, setQuestionTypes] = useState([]);
  const [questions, setQuestions] = useState([]);
  const [newQuestionText, setNewQuestionText] = useState('');
  const [newQuestionTypeId, setNewQuestionTypeId] = useState('');
  /** Option rows when creating a dropdown-type question (saved to `orac_question_options`). */
  const [newQuestionOptionRows, setNewQuestionOptionRows] = useState(['']);
  const [expandedQuestionId, setExpandedQuestionId] = useState(null);
  const [optionsByQuestion, setOptionsByQuestion] = useState({});
  const [newOptionText, setNewOptionText] = useState({});
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');

  const copy = MODE_COPY[mode] || MODE_COPY.list;
  const showList = mode === 'list';
  const showAdd = mode === 'add';

  const loadQuestions = useCallback(async () => {
    const [qt, q] = await Promise.all([
      fetchOracQuestionTypes().catch(() => []),
      fetchOracQuestionsList().catch(() => [])
    ]);
    setQuestionTypes(Array.isArray(qt) ? qt : []);
    setQuestions(Array.isArray(q) ? q : []);
  }, []);

  useEffect(() => {
    setLoading(true);
    setError('');
    loadQuestions()
      .catch((e) => setError(e.message || 'Failed to load data'))
      .finally(() => setLoading(false));
  }, [loadQuestions]);

  useEffect(() => {
    if (questionTypes.length && newQuestionTypeId === '') {
      setNewQuestionTypeId(String(questionTypes[0].question_type_id));
    }
  }, [questionTypes, newQuestionTypeId]);

  const typeLabelById = useMemo(() => {
    const m = {};
    for (const t of questionTypes) {
      m[t.question_type_id] = t.question_type || `Type ${t.question_type_id}`;
    }
    return m;
  }, [questionTypes]);

  const selectedTypeLabel = typeLabelById[Number(newQuestionTypeId)] || '';
  const creatingDropdown = isDropdownQuestionType(selectedTypeLabel);

  useEffect(() => {
    if (!creatingDropdown) {
      setNewQuestionOptionRows(['']);
    }
  }, [creatingDropdown, newQuestionTypeId]);

  const showMsg = (text, isErr = false) => {
    setMessage(text);
    setError(isErr ? text : '');
    if (!isErr) {
      window.setTimeout(() => setMessage(''), 4000);
    }
  };

  const handleAddQuestion = async (e) => {
    e.preventDefault();
    const text = newQuestionText.trim();
    const tid = Number(newQuestionTypeId);
    if (!text) {
      showMsg('Enter question text', true);
      return;
    }
    if (!Number.isInteger(tid) || tid <= 0) {
      showMsg('Select a question type', true);
      return;
    }
    setBusy(true);
    setError('');
    try {
      const created = await createOracQuestion({ question: text, question_type_id: tid });
      const newId = created?.insertedId != null ? Number(created.insertedId) : null;
      const typeLabel = typeLabelById[tid] || '';
      if (isDropdownQuestionType(typeLabel) && Number.isInteger(newId) && newId > 0) {
        const optionTexts = newQuestionOptionRows.map((s) => String(s).trim()).filter(Boolean);
        for (const opt of optionTexts) {
          await createOracQuestionOption({ question_id: newId, _options: opt });
        }
      }
      setNewQuestionText('');
      setNewQuestionOptionRows(['']);
      await loadQuestions();
      showMsg('Question added');
    } catch (err) {
      setError(err.message || 'Could not add question');
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteQuestion = async (row) => {
    if (
      !window.confirm(
        `Delete this question?\n\n${row.question}\n\nMappings and options that depend on it may block deletion.`
      )
    ) {
      return;
    }
    setBusy(true);
    setError('');
    try {
      await deleteOracQuestion(row.question_id, row.question_type_id);
      await loadQuestions();
      if (expandedQuestionId === row.question_id) setExpandedQuestionId(null);
      showMsg('Question deleted');
    } catch (err) {
      setError(err.message || 'Could not delete question');
    } finally {
      setBusy(false);
    }
  };

  const loadOptionsForQuestion = async (qid) => {
    const rows = await fetchOracQuestionOptionsByQuestionId(qid);
    setOptionsByQuestion((prev) => ({ ...prev, [qid]: rows }));
  };

  const handleToggleOptions = async (qid) => {
    if (expandedQuestionId === qid) {
      setExpandedQuestionId(null);
      return;
    }
    setExpandedQuestionId(qid);
    if (!optionsByQuestion[qid]) {
      await loadOptionsForQuestion(qid);
    }
  };

  const handleAddOption = async (questionId) => {
    const text = (newOptionText[questionId] || '').trim();
    if (!text) return;
    setBusy(true);
    setError('');
    try {
      await createOracQuestionOption({ question_id: questionId, _options: text });
      setNewOptionText((prev) => ({ ...prev, [questionId]: '' }));
      await loadOptionsForQuestion(questionId);
      showMsg('Option added');
    } catch (err) {
      setError(err.message || 'Could not add option');
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteOption = async (opt) => {
    if (!window.confirm('Remove this answer option?')) return;
    setBusy(true);
    setError('');
    try {
      await deleteOracQuestionOption(opt.question_options_id, opt.question_id);
      await loadOptionsForQuestion(opt.question_id);
      showMsg('Option removed');
    } catch (err) {
      setError(err.message || 'Could not remove option');
    } finally {
      setBusy(false);
    }
  };

  if (loading) {
    return (
      <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page">
        <p style={{ textAlign: 'center', padding: 40, color: 'var(--theme-gray-500)' }}>Loading…</p>
      </main>
    );
  }

  return (
    <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page">
      <header className="admin-page-header">
        <div>
          <div className="admin-page-badge">Admin</div>
          <h1>{copy.title}</h1>
          <p style={{ margin: '8px 0 0', fontSize: 14, color: 'var(--theme-gray-500)' }}>{copy.lead}</p>
        </div>
      </header>

      {error && (
        <p className="admin-form-builder-msg admin-form-builder-msg--err" role="alert">
          {error}
        </p>
      )}
      {message && !error && <p className="admin-form-builder-msg admin-form-builder-msg--ok">{message}</p>}

      {showList && (
        <div className="admin-questions-tab-body" id="admin-questions-panel-list" role="region" aria-label="Questions">
          <div className="admin-form-builder-table-wrap">
            <table className="admin-form-builder-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Question</th>
                <th>Type</th>
                <th />
              </tr>
            </thead>
            <tbody>
              {questions.length === 0 && (
                <tr>
                  <td colSpan={4} style={{ color: 'var(--theme-gray-400)' }}>
                    No questions yet.
                  </td>
                </tr>
              )}
              {questions.map((row) => (
                <tr key={`${row.question_id}-${row.question_type_id}`}>
                  <td>{row.question_id}</td>
                  <td>{row.question}</td>
                  <td>{typeLabelById[row.question_type_id] || row.question_type_id}</td>
                  <td style={{ whiteSpace: 'nowrap' }}>
                    {isDropdownQuestionType(typeLabelById[row.question_type_id] || '') ? (
                      <button
                        type="button"
                        className="admin-outline-button"
                        style={{ marginRight: 8 }}
                        onClick={() => handleToggleOptions(row.question_id)}
                        disabled={busy}
                      >
                        {expandedQuestionId === row.question_id ? 'Hide options' : 'Options'}
                      </button>
                    ) : (
                      <span style={{ color: 'var(--theme-gray-400)', marginRight: 8 }}>—</span>
                    )}
                    {mode === 'list' && (
                      <button
                        type="button"
                        className="admin-form-builder-danger"
                        onClick={() => handleDeleteQuestion(row)}
                        disabled={busy}
                      >
                        Delete
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
            </table>
          </div>

          {expandedQuestionId != null && (
            <div className="admin-questions-inline-options">
              <p style={{ margin: '0 0 8px', fontSize: 13, color: 'var(--theme-gray-600)' }}>
                Answer choices for question ID {expandedQuestionId} (used when the snap UI renders a select control).
              </p>
              <div className="admin-form-builder-form-row">
                <div className="admin-form-builder-field">
                  <label htmlFor="opt-text">New option</label>
                  <input
                    id="opt-text"
                    value={newOptionText[expandedQuestionId] || ''}
                    onChange={(ev) =>
                      setNewOptionText((prev) => ({ ...prev, [expandedQuestionId]: ev.target.value }))
                    }
                    placeholder="Option label"
                    disabled={busy}
                  />
                </div>
                <button
                  type="button"
                  className="admin-action-button"
                  onClick={() => handleAddOption(expandedQuestionId)}
                  disabled={busy}
                >
                  Add option
                </button>
              </div>
              <ul style={{ margin: '12px 0 0', paddingLeft: 18, fontSize: 14 }}>
                {(optionsByQuestion[expandedQuestionId] || []).map((opt) => (
                  <li key={`${opt.question_options_id}-${opt.question_id}`} style={{ marginBottom: 6 }}>
                    {opt._options || '—'}{' '}
                    <button
                      type="button"
                      className="admin-form-builder-danger"
                      style={{ marginLeft: 8 }}
                      onClick={() => handleDeleteOption(opt)}
                      disabled={busy}
                    >
                      Remove
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}

      {showAdd && (
        <div className="admin-form-builder-panel" id="admin-questions-panel-create" role="region" aria-label="Add question">
          <h2>Create question</h2>
          <p className="admin-form-builder-hint">
            For multiple dropdown (and similar) types, add answer options below before saving.
          </p>

          <form onSubmit={handleAddQuestion} className="admin-form-builder-grid">
            <div className="admin-form-builder-field">
              <label htmlFor="new-q-text">Question text</label>
              <input
                id="new-q-text"
                value={newQuestionText}
                onChange={(ev) => setNewQuestionText(ev.target.value)}
                placeholder="e.g. Was PPE worn correctly?"
                disabled={busy}
              />
            </div>
            <div className="admin-form-builder-field">
              <label htmlFor="new-q-type">Type</label>
              <select
                id="new-q-type"
                value={newQuestionTypeId}
                onChange={(ev) => setNewQuestionTypeId(ev.target.value)}
                disabled={busy || !questionTypes.length}
              >
                {questionTypes.map((t) => (
                  <option key={t.question_type_id} value={String(t.question_type_id)}>
                    {t.question_type || `Type ${t.question_type_id}`}
                  </option>
                ))}
              </select>
            </div>
            {creatingDropdown && (
              <div className="admin-form-builder-field" style={{ gridColumn: '1 / -1' }}>
                <label htmlFor="new-q-opt-0">Answer options</label>
                <p className="admin-form-builder-hint" style={{ marginTop: 4 }}>
                  Stored in the question-options table and shown as dropdown choices in the snap form.
                </p>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
                  {newQuestionOptionRows.map((row, idx) => (
                    <div key={`opt-row-${idx}`} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                      <input
                        id={idx === 0 ? 'new-q-opt-0' : undefined}
                        type="text"
                        value={row}
                        onChange={(ev) =>
                          setNewQuestionOptionRows((prev) =>
                            prev.map((v, i) => (i === idx ? ev.target.value : v))
                          )
                        }
                        placeholder={`Option ${idx + 1}`}
                        disabled={busy}
                        style={{ flex: 1 }}
                        aria-label={`Dropdown option ${idx + 1}`}
                      />
                      <button
                        type="button"
                        className="admin-outline-button"
                        disabled={busy || newQuestionOptionRows.length <= 1}
                        onClick={() =>
                          setNewQuestionOptionRows((prev) => prev.filter((_, i) => i !== idx))
                        }
                      >
                        Remove
                      </button>
                    </div>
                  ))}
                  <button
                    type="button"
                    className="admin-outline-button"
                    style={{ alignSelf: 'flex-start' }}
                    disabled={busy}
                    onClick={() => setNewQuestionOptionRows((prev) => [...prev, ''])}
                  >
                    Add option
                  </button>
                </div>
              </div>
            )}
            <div className="admin-form-builder-actions" style={{ gridColumn: '1 / -1' }}>
              <button type="submit" className="admin-action-button" disabled={busy}>
                Add question
              </button>
            </div>
          </form>
        </div>
      )}
    </main>
  );
}

export default AdminQuestionsPage;
