import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  fetchOracQuestionsList,
  fetchSectionWithQuestions,
  unmapQuestionFromSection
} from '../../api.js';
import { mapQuestionToSectionIncludingCombinedChildren } from '../../utils/oracCombinedSectionMap.js';
import { buildSectionQuestionGroups } from '../../utils/oracQuestionGroups.js';
import './admin-shared.css';
import './AdminFormBuilderPage.css';
import './AdminFormsCompositionPage.css';

/**
 * @param {{ section_id: number, title?: string }} section
 * @param {() => void} onBack - Return to section list (after Done / Save)
 */
function AdminSectionDetailPage({ section, onBack }) {
  const sectionId = section?.section_id;
  const [detail, setDetail] = useState(null);
  const [questions, setQuestions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [successDialog, setSuccessDialog] = useState({ open: false, title: '', body: '' });

  function openSuccessDialog(title, body) {
    setSuccessDialog({ open: true, title, body });
  }

  function closeSuccessDialog() {
    setSuccessDialog((s) => ({ ...s, open: false }));
  }

  useEffect(() => {
    if (!successDialog.open) return undefined;
    function onKey(e) {
      if (e.key === 'Escape') setSuccessDialog((s) => ({ ...s, open: false }));
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [successDialog.open]);

  const load = useCallback(async () => {
    if (sectionId == null || !Number.isFinite(Number(sectionId))) return;
    const id = Number(sectionId);
    const [d, q] = await Promise.all([
      fetchSectionWithQuestions(id).catch(() => null),
      fetchOracQuestionsList().catch(() => [])
    ]);
    setDetail(d ?? { section_id: id, title: section?.title, questions: [] });
    setQuestions(Array.isArray(q) ? q : []);
  }, [sectionId, section?.title]);

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

  const linked = detail?.questions || [];
  const questionGroups = useMemo(() => {
    const g = buildSectionQuestionGroups(linked);
    /* Fallback: if grouping yields nothing but API returned rows (e.g. id type quirks), show flat list */
    if (g.length > 0 || linked.length === 0) return g;
    return linked.map((q) => ({ main: q, children: [], orphan: true }));
  }, [linked]);
  const linkedIds = useMemo(
    () => new Set(linked.map((q) => Number(q.question_id)).filter((n) => Number.isFinite(n))),
    [linked]
  );
  const pool = useMemo(
    () =>
      questions.filter(
        (q) =>
          !linkedIds.has(Number(q.question_id)) &&
          (q.main_question_id == null || q.main_question_id === '')
      ),
    [questions, linkedIds]
  );

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

  const refresh = async () => {
    const id = Number(sectionId);
    const d = await fetchSectionWithQuestions(id).catch(() => null);
    setDetail(d ?? { section_id: id, questions: [] });
  };

  const handleLinkQuestion = async (e) => {
    e.preventDefault();
    const ids = [...e.currentTarget.querySelectorAll('input[name="question_ids"]:checked')]
      .map((el) => Number(el.value))
      .filter((n) => Number.isInteger(n) && n > 0);
    if (ids.length === 0) {
      showMsg('Select one or more questions to add.', true);
      return;
    }
    setBusy(true);
    setError('');
    try {
      const sid = Number(sectionId);
      const linkedSet = new Set(linked.map((q) => Number(q.question_id)).filter((n) => Number.isFinite(n)));
      let extraChildren = 0;
      for (const qid of ids) {
        const { addedChildren } = await mapQuestionToSectionIncludingCombinedChildren(sid, qid, linkedSet);
        extraChildren += addedChildren;
      }
      await refresh();
      e.currentTarget.querySelectorAll('input[name="question_ids"]').forEach((el) => {
        el.checked = false;
      });
      if (extraChildren > 0) {
        openSuccessDialog(
          'Questions added',
          `Added ${ids.length} selection(s) and ${extraChildren} combined child question(s) (e.g. L/S under RPN).`
        );
      } else {
        openSuccessDialog(
          ids.length === 1 ? 'Question added' : 'Questions added',
          ids.length === 1
            ? 'The question was added to this section.'
            : `${ids.length} questions were added to this section.`
        );
      }
    } catch (err) {
      setError(err.message || 'Could not link one or more questions');
      await refresh();
    } finally {
      setBusy(false);
    }
  };

  const handleUnlinkQuestion = async (questionId) => {
    if (!window.confirm('Remove this question from the section?')) return;
    const row = linked.find((q) => Number(q.question_id) === Number(questionId));
    const childIds = Array.isArray(row?.child_question_ids) ? row.child_question_ids : [];
    setBusy(true);
    setError('');
    try {
      const sid = Number(sectionId);
      for (const cid of childIds) {
        await unmapQuestionFromSection(sid, cid);
      }
      await unmapQuestionFromSection(sid, questionId);
      await refresh();
      openSuccessDialog(
        'Question removed',
        childIds.length
          ? `Removed the question and ${childIds.length} combined child question(s).`
          : 'The question was removed from this section.'
      );
    } catch (err) {
      setError(err.message || 'Could not remove question');
    } finally {
      setBusy(false);
    }
  };

  const title = detail?.title || section?.title || `Section ${sectionId}`;

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

  return (
    <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-section-detail">
      <header className="admin-page-header admin-page-header--with-actions admin-section-detail__toolbar">
        <div>
          <div className="admin-page-badge">Admin · Section</div>
          <h1>{title}</h1>
          <p className="admin-section-detail__lead">
            Section id {sectionId}. Combined parents (<code>orac_combined_question</code>) only show mains in the bank;
            children attach automatically. Select <strong>one or more</strong> questions below and add them together. Use{' '}
            <strong>Save &amp; return</strong> when you are done.
          </p>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" className="admin-outline-button" onClick={onBack} disabled={busy}>
            ← Back to list
          </button>
          <button type="button" className="admin-action-button" onClick={onBack} disabled={busy}>
            Save &amp; return to list
          </button>
        </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>}

      <div className="admin-section-detail__list-heading">
        <h2>Questions in this section</h2>
        <p className="admin-form-builder-hint">
          Create questions on the <strong>ORAC questions</strong> page first, then add them below.
        </p>
      </div>

      <div className="admin-section-detail__list-scroll" role="region" aria-label="Questions in this section">
        {linked.length === 0 ? (
          <div className="admin-section-detail__empty">
            No questions linked yet. Use the checkboxes below to add one or more from the bank.
          </div>
        ) : (
          <ul className="admin-section-detail__list">
            {questionGroups.map((g) => (
              <li key={g.main.question_id} className="admin-section-detail__row admin-section-detail__row--group">
                <div className="admin-section-detail__row-head">
                  <div className="admin-section-detail__qtext">
                    {g.main.question}
                    <span className="admin-section-detail__qid">#{g.main.question_id}</span>
                    {g.children.length > 0 && (
                      <span style={{ fontSize: 12, color: 'var(--theme-gray-500)', marginLeft: 6 }}>
                        + {g.children.length} combined
                      </span>
                    )}
                  </div>
                  <button
                    type="button"
                    className="admin-form-builder-danger"
                    onClick={() => handleUnlinkQuestion(g.main.question_id)}
                    disabled={busy}
                  >
                    Remove
                  </button>
                </div>
                {g.children.length > 0 && (
                  <ul className="admin-section-detail__combined-children">
                    {g.children.map((c) => (
                      <li key={c.question_id}>
                        {c.question}
                        <span className="admin-section-detail__qid"> #{c.question_id}</span>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>

      <div className="admin-section-detail__footer">
        <form onSubmit={handleLinkQuestion} className="admin-section-detail__add-form">
          <fieldset className="admin-section-detail__fieldset" disabled={busy || !pool.length}>
            <legend className="admin-section-detail__legend">Add questions from bank</legend>
            <p className="admin-form-builder-hint admin-section-detail__add-hint">
              Select <strong>one or more</strong> questions (checkboxes), then add them to this section in one go. You can
              repeat to attach more later.
            </p>
            {pool.length === 0 ? (
              <p className="admin-section-detail__pool-empty">Every question in the bank is already in this section.</p>
            ) : (
              <div className="admin-section-detail__checkboxes" role="group" aria-label="Questions available to add">
                {pool.map((q) => (
                  <label key={q.question_id} className="admin-section-detail__pick-row">
                    <input type="checkbox" name="question_ids" value={String(q.question_id)} />
                    <span className="admin-section-detail__pick-text">
                      {q.question}
                      <span className="admin-section-detail__qid"> #{q.question_id}</span>
                    </span>
                  </label>
                ))}
              </div>
            )}
          </fieldset>
          <div className="admin-section-detail__add-actions">
            <button type="submit" className="admin-action-button" disabled={busy || !pool.length}>
              Add selected to section
            </button>
          </div>
        </form>

        <div className="admin-section-detail__footer-actions">
          <button type="button" className="admin-action-button" onClick={onBack} disabled={busy}>
            Save &amp; return to section list
          </button>
        </div>
      </div>

      {successDialog.open && (
        <div
          className="admin-orac-form-popup-overlay"
          role="dialog"
          aria-modal="true"
          aria-labelledby="admin-section-detail-success-title"
          onClick={(e) => {
            if (e.target === e.currentTarget) closeSuccessDialog();
          }}
        >
          <div className="admin-orac-form-popup-dialog">
            <h3 id="admin-section-detail-success-title">{successDialog.title}</h3>
            <p>{successDialog.body}</p>
            <button type="button" className="admin-action-button admin-orac-form-popup-ok" onClick={closeSuccessDialog}>
              OK
            </button>
          </div>
        </div>
      )}
    </main>
  );
}

export default AdminSectionDetailPage;
