import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  createOracSectionDetail,
  deleteOracSectionDetail,
  fetchOracQuestionsList,
  fetchOracSectionDetailsList
} from '../../api.js';
import { getSessionUserId } from './adminOracSession.js';
import { mapQuestionToSectionIncludingCombinedChildren } from '../../utils/oracCombinedSectionMap.js';
import './admin-shared.css';
import './AdminFormBuilderPage.css';
import './AdminFormsCompositionPage.css';

const MODE_COPY = {
  list: {
    title: 'Section list',
    lead:
      'All ORAC sections. Open a section to manage which questions belong to it, or delete a section from here.'
  },
  add: {
    title: 'Add section',
    lead:
      'Create a section by title and map at least one question from the bank. Combined questions (e.g. RPN with L/S) add their children automatically.'
  },
  edit: {
    title: 'Edit section',
    lead: 'Choose a section and open it to change its questions and settings.'
  }
};

function AdminSectionsPage({ mode = 'list', onOpenSection, onNavigateToSectionList }) {
  const [sections, setSections] = useState([]);
  const [newSectionTitle, setNewSectionTitle] = useState('');
  const [questions, setQuestions] = useState([]);
  const [questionsLoading, setQuestionsLoading] = useState(false);
  const [questionsLoadError, setQuestionsLoadError] = useState('');
  const [selectedQuestionIds, setSelectedQuestionIds] = 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 }));

    if (mode === 'add' && typeof onNavigateToSectionList === 'function') {
      onNavigateToSectionList();
    }
  }

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

  const uid = getSessionUserId();
  const copy = MODE_COPY[mode] || MODE_COPY.list;
  const showList = mode === 'list' || mode === 'edit';
  const showAdd = mode === 'add';
  const openActionLabel = mode === 'edit' ? 'Edit' : 'Open';

  const questionPool = useMemo(
    () =>
      questions.filter(
        (q) => q.main_question_id == null || q.main_question_id === ''
      ),
    [questions]
  );

  useEffect(() => {
    if (!showAdd) return undefined;
    let cancelled = false;
    setQuestionsLoading(true);
    setQuestionsLoadError('');
    fetchOracQuestionsList()
      .then((rows) => {
        if (!cancelled) setQuestions(Array.isArray(rows) ? rows : []);
      })
      .catch((e) => {
        if (!cancelled) setQuestionsLoadError(e.message || 'Failed to load questions');
      })
      .finally(() => {
        if (!cancelled) setQuestionsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [showAdd]);

  useEffect(() => {
    if (!showAdd) setSelectedQuestionIds([]);
  }, [showAdd]);

  const toggleQuestionInPool = (questionId) => {
    const qid = Number(questionId);
    if (!Number.isInteger(qid) || qid <= 0) return;
    setSelectedQuestionIds((prev) =>
      prev.includes(qid) ? prev.filter((x) => x !== qid) : [...prev, qid]
    );
  };

  const idsToMapForSubmit = useMemo(
    () => selectedQuestionIds.filter((n) => Number.isInteger(n) && n > 0),
    [selectedQuestionIds]
  );

  const canSubmitCreateSection =
    showAdd &&
    !questionsLoading &&
    !questionsLoadError &&
    questionPool.length > 0 &&
    idsToMapForSubmit.length > 0 &&
    newSectionTitle.trim().length > 0;

  const loadSections = useCallback(async () => {
    const s = await fetchOracSectionDetailsList().catch(() => []);
    setSections(Array.isArray(s) ? s : []);
  }, []);

  useEffect(() => {
    if (!showList) {
      setLoading(false);
      setError('');
      return;
    }
    setLoading(true);
    setError('');
    loadSections()
      .catch((e) => setError(e.message || 'Failed to load sections'))
      .finally(() => setLoading(false));
  }, [loadSections, showList]);

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

  const handleAddSection = async (e) => {
    e.preventDefault();
    const title = newSectionTitle.trim();
    if (!title) {
      showMsg('Enter section title', true);
      return;
    }
    const idsToMap = selectedQuestionIds.filter((n) => Number.isInteger(n) && n > 0);
    if (idsToMap.length === 0) {
      showMsg('Select at least one question to add to this section.', true);
      return;
    }
    if (questionPool.length === 0 && !questionsLoading && !questionsLoadError) {
      showMsg('There are no questions in the bank. Create questions on the ORAC questions page first.', true);
      return;
    }
    setBusy(true);
    setError('');
    try {
      const body = { title };
      if (uid != null && Number.isFinite(uid)) body.created_by = uid;
      const res = await createOracSectionDetail(body);
      const rawId = res?.insertedId ?? res?.insertId;
      const sectionId = rawId != null ? Number(rawId) : NaN;
      if (!Number.isInteger(sectionId) || sectionId <= 0) {
        throw new Error('Section was created but no id was returned from the server.');
      }

      let extraChildren = 0;
      const linkedSet = new Set();
      for (const qid of idsToMap) {
        const { addedChildren } = await mapQuestionToSectionIncludingCombinedChildren(
          sectionId,
          qid,
          linkedSet
        );
        extraChildren += addedChildren;
      }

      setNewSectionTitle('');
      setSelectedQuestionIds([]);

      const base = `Section #${sectionId} was created with ${idsToMap.length} question selection(s) mapped.`;
      const extra =
        extraChildren > 0
          ? ` ${extraChildren} combined child question(s) (e.g. L/S under RPN) were added automatically.`
          : '';
      openSuccessDialog('Section created', `${base}${extra}`);
    } catch (err) {
      setError(err.message || 'Could not create section');
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteSection = async (row) => {
    if (!window.confirm(`Delete section "${row.title || row.section_id}"?`)) return;
    setBusy(true);
    setError('');
    try {
      await deleteOracSectionDetail(row.section_id);
      await loadSections();
      showMsg('Section deleted');
    } catch (err) {
      setError(err.message || 'Could not delete section');
    } finally {
      setBusy(false);
    }
  };

  if (loading && showList) {
    return (
      <main className="dashboard-main admin-dashboard admin-dashboard-v2 admin-form-builder admin-orac-page admin-orac-sections-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 admin-orac-sections-page">
      <header className="admin-page-header admin-orac-sections-page__header">
        <div>
          <div className="admin-page-badge">Admin</div>
          <h1>{copy.title}</h1>
          <p className="admin-orac-sections-page__lead">{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>}

      {showAdd && (
        <div className="admin-form-builder-panel admin-orac-sections-page__panel">
          <h2>Create a section</h2>
          <p className="admin-form-builder-hint admin-orac-sections-page__hint">
            Enter a title and select <strong>at least one</strong> question below. Questions must exist on the{' '}
            <strong>ORAC questions</strong> page first.
          </p>

          <form onSubmit={handleAddSection} className="admin-form-builder-grid admin-orac-sections-page__form">
            <div className="admin-form-builder-field" style={{ gridColumn: '1 / -1' }}>
              <label htmlFor="new-sec-title">New section title</label>
              <input
                id="new-sec-title"
                value={newSectionTitle}
                onChange={(ev) => setNewSectionTitle(ev.target.value)}
                placeholder="e.g. Housekeeping"
                disabled={busy}
              />
            </div>

            <div className="admin-section-detail__add-form" style={{ gridColumn: '1 / -1' }}>
              <fieldset className="admin-section-detail__fieldset" disabled={busy || questionsLoading}>
                <legend className="admin-section-detail__legend">Add questions — required</legend>
                <p className="admin-form-builder-hint admin-section-detail__add-hint">
                  Select <strong>one or more</strong> main questions (required). Combined groups (RPN + L/S) attach
                  children automatically, same as on the section detail page.
                </p>
                {questionsLoadError && (
                  <p className="admin-form-builder-msg admin-form-builder-msg--err" role="alert">
                    {questionsLoadError}
                  </p>
                )}
                {questionsLoading && (
                  <p className="admin-form-builder-hint" style={{ marginTop: 0 }}>
                    Loading question bank…
                  </p>
                )}
                {!questionsLoading && !questionsLoadError && questionPool.length === 0 && (
                  <p className="admin-section-detail__pool-empty">
                    No questions in the bank yet. Create questions on the ORAC questions page, then return here.
                  </p>
                )}
                {!questionsLoading && questionPool.length > 0 && (
                  <div
                    className="admin-section-detail__checkboxes admin-orac-form-add-questions__box"
                    role="group"
                    aria-label="Questions to map to this section (select at least one)"
                  >
                    {questionPool.map((q) => (
                      <label key={q.question_id} className="admin-section-detail__pick-row">
                        <input
                          type="checkbox"
                          checked={selectedQuestionIds.includes(Number(q.question_id))}
                          onChange={() => toggleQuestionInPool(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>

            <div className="admin-form-builder-actions" style={{ gridColumn: '1 / -1' }}>
              <button
                type="submit"
                className="admin-action-button"
                disabled={busy || !canSubmitCreateSection}
                title={
                  canSubmitCreateSection || busy
                    ? undefined
                    : 'Enter a title and select at least one question'
                }
              >
                {busy ? 'Creating…' : 'Create section'}
              </button>
            </div>
          </form>
        </div>
      )}

      {showList && (
        <div className="admin-form-builder-panel admin-orac-sections-page__panel">
          <div className="admin-orac-sections-all">
            <h2>{mode === 'edit' ? 'Choose a section' : 'All sections'}</h2>
            <p className="admin-form-builder-hint admin-orac-sections-all__hint">
              {mode === 'edit' ? (
                <>
                  Click <strong>Edit</strong> to open that section&apos;s page and manage questions.
                </>
              ) : (
                <>
                  Click <strong>Open</strong> to manage questions for that section.
                </>
              )}
            </p>

            <div className="admin-form-builder-table-wrap admin-orac-sections-table-wrap">
              <table className="admin-form-builder-table">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th style={{ width: '1%' }}>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {sections.length === 0 && (
                    <tr>
                      <td colSpan={3} style={{ color: 'var(--theme-gray-400)' }}>
                        No sections yet. Add one under Add section.
                      </td>
                    </tr>
                  )}
                  {sections.map((row) => (
                    <tr key={row.section_id}>
                      <td>{row.section_id}</td>
                      <td>{row.title || '—'}</td>
                      <td style={{ whiteSpace: 'nowrap' }}>
                        <button
                          type="button"
                          className="admin-action-button"
                          style={{ marginRight: 8 }}
                          onClick={() =>
                            onOpenSection({
                              section_id: row.section_id,
                              title: row.title || ''
                            })
                          }
                          disabled={busy}
                        >
                          {openActionLabel}
                        </button>
                        {mode === 'list' && (
                          <button
                            type="button"
                            className="admin-form-builder-danger"
                            onClick={() => handleDeleteSection(row)}
                            disabled={busy}
                          >
                            Delete
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {successDialog.open && (
        <div
          className="admin-orac-form-popup-overlay"
          role="dialog"
          aria-modal="true"
          aria-labelledby="admin-section-create-success-title"
          onClick={(e) => {
            if (e.target === e.currentTarget) closeSuccessDialog();
          }}
        >
          <div className="admin-orac-form-popup-dialog">
            <h3 id="admin-section-create-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 AdminSectionsPage;
