import React, { useState } from "react";
import { publishNestedForm } from "../../../services/formsApi.js";

const initialState = {
  form: { title: "", description: "", form_type_id: "", job_type_id: "" },
  location_ids: "",
  sections: [{ title: "", order: 1, question: "", question_type_id: "", allows_media: false, options: "" }]
};

function toPayload(state) {
  return {
    form: {
      title: state.form.title,
      description: state.form.description,
      form_type_id: state.form.form_type_id ? Number(state.form.form_type_id) : null,
      job_type_id: state.form.job_type_id ? Number(state.form.job_type_id) : null
    },
    location_ids: String(state.location_ids || "")
      .split(",")
      .map((v) => Number(v.trim()))
      .filter((n) => Number.isInteger(n) && n > 0),
    sections: state.sections
      .filter((section) => section.title.trim() && section.question.trim())
      .map((section, index) => ({
        title: section.title.trim(),
        order: Number(section.order) || index + 1,
        questions: [
          {
            question: section.question.trim(),
            question_type_id: section.question_type_id ? Number(section.question_type_id) : null,
            allows_media: section.allows_media ? 1 : 0,
            options: String(section.options || "")
              .split(",")
              .map((item) => item.trim())
              .filter(Boolean)
          }
        ]
      }))
  };
}

export default function NestedFormPublishPanel() {
  const [open, setOpen] = useState(false);
  const [state, setState] = useState(initialState);
  const [status, setStatus] = useState("");
  const [saving, setSaving] = useState(false);

  const setFormField = (key, value) => setState((prev) => ({ ...prev, form: { ...prev.form, [key]: value } }));
  const setSectionField = (index, key, value) => {
    setState((prev) => ({
      ...prev,
      sections: prev.sections.map((section, i) => (i === index ? { ...section, [key]: value } : section))
    }));
  };

  const addSection = () => {
    setState((prev) => ({
      ...prev,
      sections: [...prev.sections, { title: "", order: prev.sections.length + 1, question: "", question_type_id: "", allows_media: false, options: "" }]
    }));
  };

  const removeSection = (index) => {
    setState((prev) => ({ ...prev, sections: prev.sections.filter((_, i) => i !== index) }));
  };

  const handlePublish = async () => {
    setSaving(true);
    try {
      await publishNestedForm(toPayload(state));
      setStatus("Nested form published successfully.");
      setState(initialState);
    } catch (err) {
      setStatus(err?.response?.data?.message || err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="ptw-nested-publish">
      <button type="button" className="swi-btn swi-btn--ghost" onClick={() => setOpen((prev) => !prev)}>
        {open ? "Hide advanced — publish nested form" : "Advanced — publish nested form"}
      </button>
      {open ? (
        <div style={{ marginTop: "0.9rem" }}>
          <div className="ptw-form-grid-2">
            <label className="swi-field">
              <span className="swi-field__label">Form title</span>
              <input className="swi-input" value={state.form.title} onChange={(e) => setFormField("title", e.target.value)} />
            </label>
            <label className="swi-field">
              <span className="swi-field__label">Form type id</span>
              <input className="swi-input" value={state.form.form_type_id} onChange={(e) => setFormField("form_type_id", e.target.value)} />
            </label>
            <label className="swi-field">
              <span className="swi-field__label">Job type id</span>
              <input className="swi-input" value={state.form.job_type_id} onChange={(e) => setFormField("job_type_id", e.target.value)} />
            </label>
            <label className="swi-field">
              <span className="swi-field__label">Location ids (comma separated)</span>
              <input className="swi-input" value={state.location_ids} onChange={(e) => setState((prev) => ({ ...prev, location_ids: e.target.value }))} />
            </label>
            <label className="swi-field" style={{ gridColumn: "1 / -1" }}>
              <span className="swi-field__label">Description</span>
              <textarea className="swi-input" rows={3} value={state.form.description} onChange={(e) => setFormField("description", e.target.value)} />
            </label>
          </div>

          {state.sections.map((section, index) => (
            <div key={`section-${index}`} className="ptw-builder-section">
              <div className="ptw-builder-section__head">
                <strong>Section {index + 1}</strong>
                <button type="button" className="swi-btn swi-btn--ghost" onClick={() => removeSection(index)} disabled={state.sections.length === 1}>Remove</button>
              </div>
              <div className="ptw-form-grid-2">
                <label className="swi-field">
                  <span className="swi-field__label">Section title</span>
                  <input className="swi-input" value={section.title} onChange={(e) => setSectionField(index, "title", e.target.value)} />
                </label>
                <label className="swi-field">
                  <span className="swi-field__label">Section order</span>
                  <input className="swi-input" type="number" value={section.order} onChange={(e) => setSectionField(index, "order", e.target.value)} />
                </label>
                <label className="swi-field" style={{ gridColumn: "1 / -1" }}>
                  <span className="swi-field__label">Question</span>
                  <textarea className="swi-input" rows={2} value={section.question} onChange={(e) => setSectionField(index, "question", e.target.value)} />
                </label>
                <label className="swi-field">
                  <span className="swi-field__label">Question type id</span>
                  <input className="swi-input" type="number" value={section.question_type_id} onChange={(e) => setSectionField(index, "question_type_id", e.target.value)} />
                </label>
                <label className="swi-field">
                  <span className="swi-field__label">Options (comma separated)</span>
                  <input className="swi-input" value={section.options} onChange={(e) => setSectionField(index, "options", e.target.value)} />
                </label>
                <label className="swi-check">
                  <input type="checkbox" checked={Boolean(section.allows_media)} onChange={(e) => setSectionField(index, "allows_media", e.target.checked)} />
                  <span>Allow media upload</span>
                </label>
              </div>
            </div>
          ))}

          <div className="ptw-row-actions">
            <button type="button" className="swi-btn swi-btn--ghost" onClick={addSection}>Add Section</button>
            <button type="button" className="swi-btn" onClick={handlePublish} disabled={saving}>Publish Nested Form</button>
          </div>
          {status ? <p className="ptw-muted" style={{ marginTop: "0.6rem" }}>{status}</p> : null}
        </div>
      ) : null}
    </div>
  );
}
