import React, { useEffect, useState } from "react";
import PageHeader from "../../components/common/PageHeader.jsx";
import DataTable from "../../components/common/DataTable.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import {
  createForm,
  createQuestion,
  createQuestionOption,
  createSection,
  deleteForm,
  listFormLogs,
  listForms,
  listSectionLogs,
  mapFormLocation,
  mapFormSection,
  mapSectionQuestion,
  publishNestedForm,
  setSkipLogic,
  updateForm
} from "../../services/formsApi.js";

const initialNested = {
  form: { title: "", description: "", form_type_id: "", job_type_id: "" },
  location_ids: [],
  sections: []
};

function emptySection(order = 1) {
  return {
    title: "",
    order,
    questions: [{ question: "", question_type_id: "", allows_media: 0, options: "" }]
  };
}

export default function AdminFormBuilderPage() {
  const [forms, setForms] = useState([]);
  const [formLogs, setFormLogs] = useState([]);
  const [sectionLogs, setSectionLogs] = useState([]);
  const [active, setActive] = useState(null);
  const [error, setError] = useState("");
  const [nested, setNested] = useState(initialNested);
  const [nestedError, setNestedError] = useState("");

  async function load() {
    try {
      const [f, fl, sl] = await Promise.all([listForms(), listFormLogs(), listSectionLogs()]);
      setForms(f);
      setFormLogs(fl);
      setSectionLogs(sl);
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    }
  }
  useEffect(() => { load(); }, []);

  const setFormField = (key, value) => {
    setNested((prev) => ({
      ...prev,
      form: { ...prev.form, [key]: value }
    }));
  };

  const setLocationIdsText = (text) => {
    const ids = text
      .split(",")
      .map((v) => Number(v.trim()))
      .filter((n) => Number.isInteger(n) && n > 0);
    setNested((prev) => ({ ...prev, location_ids: ids }));
  };

  const addSection = () => {
    setNested((prev) => {
      const nextOrder = prev.sections.length + 1;
      return { ...prev, sections: [...prev.sections, emptySection(nextOrder)] };
    });
  };

  const removeSection = (sectionIndex) => {
    setNested((prev) => ({
      ...prev,
      sections: prev.sections.filter((_, i) => i !== sectionIndex).map((sec, i) => ({
        ...sec,
        order: i + 1
      }))
    }));
  };

  const setSectionField = (sectionIndex, key, value) => {
    setNested((prev) => ({
      ...prev,
      sections: prev.sections.map((sec, i) => (i === sectionIndex ? { ...sec, [key]: value } : sec))
    }));
  };

  const addQuestionRow = (sectionIndex) => {
    setNested((prev) => ({
      ...prev,
      sections: prev.sections.map((sec, i) =>
        i === sectionIndex
          ? {
              ...sec,
              questions: [...(sec.questions || []), { question: "", question_type_id: "", allows_media: 0, options: "" }]
            }
          : sec
      )
    }));
  };

  const removeQuestionRow = (sectionIndex, questionIndex) => {
    setNested((prev) => ({
      ...prev,
      sections: prev.sections.map((sec, i) =>
        i === sectionIndex
          ? {
              ...sec,
              questions: (sec.questions || []).filter((_, qIdx) => qIdx !== questionIndex)
            }
          : sec
      )
    }));
  };

  const setQuestionField = (sectionIndex, questionIndex, key, value) => {
    setNested((prev) => ({
      ...prev,
      sections: prev.sections.map((sec, i) =>
        i === sectionIndex
          ? {
              ...sec,
              questions: (sec.questions || []).map((q, qIdx) =>
                qIdx === questionIndex ? { ...q, [key]: value } : q
              )
            }
          : sec
      )
    }));
  };

  const buildNestedPayload = () => {
    const title = String(nested.form.title || "").trim();
    if (!title) {
      throw new Error("Form title is required for nested publish.");
    }
    const sections = (nested.sections || [])
      .map((sec, idx) => {
        const sectionTitle = String(sec.title || "").trim();
        if (!sectionTitle) return null;
        const questions = (sec.questions || [])
          .map((q) => {
            const questionText = String(q.question || "").trim();
            if (!questionText) return null;
            const options = String(q.options || "")
              .split(",")
              .map((opt) => opt.trim())
              .filter(Boolean);
            return {
              question: questionText,
              question_type_id: q.question_type_id ? Number(q.question_type_id) : null,
              allows_media: Number(q.allows_media) ? 1 : 0,
              options
            };
          })
          .filter(Boolean);
        return {
          title: sectionTitle,
          order: sec.order || idx + 1,
          questions
        };
      })
      .filter(Boolean);

    return {
      form: {
        title,
        description: String(nested.form.description || "").trim(),
        form_type_id: nested.form.form_type_id ? Number(nested.form.form_type_id) : null,
        job_type_id: nested.form.job_type_id ? Number(nested.form.job_type_id) : null
      },
      location_ids: nested.location_ids || [],
      sections
    };
  };

  return (
    <div className="portal-page">
      <PageHeader title="Form Builder" subtitle="Manage forms, sections, questions, options, mappings, skip logic, and transactional publish." />
      <ErrorBanner message={error} />
      <div className="ptw-split">
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">Forms</h3>
          <div className="ptw-row-actions">
            <button type="button" className="swi-btn" onClick={async () => { await createForm({ title: `Form ${Date.now()}` }); await load(); }}>Create Form</button>
            <button type="button" className="swi-btn swi-btn--ghost" onClick={load}>Refresh</button>
          </div>
          <DataTable
            columns={[{ key: "form_id", label: "Form ID" }, { key: "title", label: "Title" }, { key: "description", label: "Description" }]}
            rows={forms}
            keyField="form_id"
            onRowClick={setActive}
          />
        </div>
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">Selected Form Actions</h3>
          {active ? (
            <>
              <p><strong>#{active.form_id}</strong> {active.title}</p>
              <div className="ptw-row-actions">
                <button type="button" className="swi-btn" onClick={async () => { await updateForm(active.form_id, { title: `${active.title} (updated)` }); await load(); }}>Update Form</button>
                <button type="button" className="swi-btn swi-btn--danger" onClick={async () => { await deleteForm(active.form_id); setActive(null); await load(); }}>Delete Form</button>
                <button type="button" className="swi-btn" onClick={async () => { await createSection({ title: `Section ${Date.now()}` }); alert("Add Section called."); }}>Add Section</button>
                <button type="button" className="swi-btn" onClick={async () => { const q = await createQuestion({ question: "New Question", allows_media: 0 }); await createQuestionOption({ question_id: q?.insertedId, _options: "Option A" }); alert("Add Question / Add Options called."); }}>Add Question</button>
                <button type="button" className="swi-btn" onClick={async () => { await mapFormLocation({ form_id: active.form_id, location_id: 1 }); alert("Map Locations called (location_id=1)."); }}>Map Locations</button>
                <button type="button" className="swi-btn" onClick={async () => { await mapFormSection({ form_id: active.form_id, section_id: 1, section_in_form_order: 1 }); alert("Map Section Order called."); }}>Map Section Order</button>
                <button type="button" className="swi-btn" onClick={async () => { await mapSectionQuestion({ section_id: 1, question_id: 1 }); await setSkipLogic({ skipable_section_id: 1, other_section_id: 1 }); alert("Set Skip Logic called."); }}>Set Skip Logic</button>
              </div>
            </>
          ) : (
            <p className="ptw-muted">Pick a form first.</p>
          )}
        </div>
      </div>
      <div className="ptw-panel">
        <h3 className="ptw-panel__title">Publish Nested Form (`POST /form-builder`)</h3>
        <ErrorBanner message={nestedError} />
        <div className="ptw-form-grid-2">
          <label className="swi-field">
            <span className="swi-field__label">Form Title</span>
            <input
              className="swi-input"
              value={nested.form.title}
              onChange={(e) => setFormField("title", e.target.value)}
              placeholder="Confined Space Entry"
            />
          </label>
          <label className="swi-field">
            <span className="swi-field__label">Description</span>
            <input
              className="swi-input"
              value={nested.form.description}
              onChange={(e) => setFormField("description", e.target.value)}
              placeholder="Form description"
            />
          </label>
          <label className="swi-field">
            <span className="swi-field__label">Form Type ID</span>
            <input
              className="swi-input"
              value={nested.form.form_type_id}
              onChange={(e) => setFormField("form_type_id", e.target.value)}
              placeholder="1"
            />
          </label>
          <label className="swi-field">
            <span className="swi-field__label">Job Type ID</span>
            <input
              className="swi-input"
              value={nested.form.job_type_id}
              onChange={(e) => setFormField("job_type_id", e.target.value)}
              placeholder="1"
            />
          </label>
        </div>
        <label className="swi-field">
          <span className="swi-field__label">Location IDs (comma-separated)</span>
          <input
            className="swi-input"
            value={(nested.location_ids || []).join(",")}
            onChange={(e) => setLocationIdsText(e.target.value)}
            placeholder="1,2,3"
          />
        </label>

        <div className="ptw-row-actions" style={{ marginBottom: "0.75rem" }}>
          <button type="button" className="swi-btn swi-btn--ghost" onClick={addSection}>
            Add Nested Section
          </button>
        </div>

        {(nested.sections || []).map((section, sectionIndex) => (
          <div className="ptw-builder-section" key={`nested-section-${sectionIndex}`}>
            <div className="ptw-builder-section__head">
              <input
                className="swi-input"
                value={section.title}
                onChange={(e) => setSectionField(sectionIndex, "title", e.target.value)}
                placeholder={`Section ${sectionIndex + 1} title`}
              />
              <button type="button" className="swi-btn swi-btn--danger" onClick={() => removeSection(sectionIndex)}>
                Remove Section
              </button>
            </div>
            {(section.questions || []).map((q, questionIndex) => (
              <div className="ptw-builder-question" key={`nested-question-${sectionIndex}-${questionIndex}`}>
                <div className="ptw-builder-question__row">
                  <input
                    className="swi-input"
                    value={q.question}
                    onChange={(e) => setQuestionField(sectionIndex, questionIndex, "question", e.target.value)}
                    placeholder="Question text"
                  />
                  <input
                    className="swi-input"
                    value={q.question_type_id}
                    onChange={(e) => setQuestionField(sectionIndex, questionIndex, "question_type_id", e.target.value)}
                    placeholder="Question Type ID"
                  />
                  <button type="button" className="swi-btn swi-btn--danger" onClick={() => removeQuestionRow(sectionIndex, questionIndex)}>
                    Remove
                  </button>
                </div>
                <div className="ptw-form-grid-2" style={{ marginTop: "0.5rem" }}>
                  <label className="swi-field">
                    <span className="swi-field__label">Options (comma-separated)</span>
                    <input
                      className="swi-input"
                      value={q.options}
                      onChange={(e) => setQuestionField(sectionIndex, questionIndex, "options", e.target.value)}
                      placeholder="Yes,No"
                    />
                  </label>
                  <label className="swi-field">
                    <span className="swi-field__label">Allows Media</span>
                    <select
                      className="swi-input"
                      value={Number(q.allows_media) ? "1" : "0"}
                      onChange={(e) => setQuestionField(sectionIndex, questionIndex, "allows_media", Number(e.target.value))}
                    >
                      <option value="0">No</option>
                      <option value="1">Yes</option>
                    </select>
                  </label>
                </div>
              </div>
            ))}
            <button type="button" className="swi-btn swi-btn--ghost" onClick={() => addQuestionRow(sectionIndex)}>
              Add Question Row
            </button>
          </div>
        ))}
        <div className="ptw-row-actions">
          <button
            type="button"
            className="swi-btn"
            onClick={async () => {
              try {
                const payload = buildNestedPayload();
                setNestedError("");
                await publishNestedForm(payload);
                await load();
              } catch (err) {
                setNestedError(err?.response?.data?.message || err.message);
              }
            }}
          >
            Publish Nested Form
          </button>
        </div>
      </div>
      <div className="ptw-split">
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">View Form Logs</h3>
          <DataTable columns={[{ key: "log_id", label: "Log" }, { key: "form_id", label: "Form" }, { key: "action", label: "Action" }, { key: "created_at", label: "At" }]} rows={formLogs} keyField="log_id" />
        </div>
        <div className="ptw-panel">
          <h3 className="ptw-panel__title">View Section Logs</h3>
          <DataTable columns={[{ key: "log_id", label: "Log" }, { key: "section_id", label: "Section" }, { key: "action", label: "Action" }, { key: "created_at", label: "At" }]} rows={sectionLogs} keyField="log_id" />
        </div>
      </div>
    </div>
  );
}
