import { formData } from "../context/TOD.FormulaireData";
import { useEffect, useState } from "react";
import "./TOD.PageSectionManager.css";
import { ArrowUp, ArrowDown } from "../../components/icons/arrow";

const PageSectionManager = ({ forms, pageName, showOrderButtons = true }) => {
  const [isInitialized, setIsInitialized] = useState(false);

  const init = () => {
    if (!formData.value[pageName]) {
      formData.value[pageName] = {};
    }

    if (!formData.value[pageName].sections) {
      formData.value[pageName].sections = [];
    }

    if (!formData.value[pageName].sectionsOrder) {
      formData.value[pageName].sectionsOrder = [];
    }

    // Initialiser les nouveaux formulaires
    forms.forEach((form) => {
      form.init(pageName);
    });

    // Nettoyer les sections qui n'existent plus
    const validTypes = forms.map((form) => form.type);
    formData.value = {
      ...formData.value,
      [pageName]: {
        ...formData.value[pageName],
        sections: formData.value[pageName].sections.filter((section) =>
          validTypes.includes(section.type)
        ),
        sectionsOrder: formData.value[pageName].sectionsOrder.filter((id) =>
          formData.value[pageName].sections.find(
            (s) => s.id === id && validTypes.includes(s.type)
          )
        ),
      },
    };

    setIsInitialized(true);
  };

  const moveSection = (index, direction) => {
    const newOrder = [...formData.value[pageName].sectionsOrder];
    if (direction === "up" && index > 0) {
      [newOrder[index], newOrder[index - 1]] = [
        newOrder[index - 1],
        newOrder[index],
      ];
    } else if (direction === "down" && index < newOrder.length - 1) {
      [newOrder[index], newOrder[index + 1]] = [
        newOrder[index + 1],
        newOrder[index],
      ];
    }
    formData.value = {
      ...formData.value,
      [pageName]: {
        ...formData.value[pageName],
        sectionsOrder: newOrder,
      },
    };
  };

  useEffect(() => {
    init();
  }, []);

  if (!isInitialized) return null;

  // Utilise sectionsOrder pour afficher les formulaires dans le bon ordre
  const orderedForms = formData.value[pageName].sectionsOrder
    .map((id) => {
      const section = formData.value[pageName].sections.find(
        (s) => s.id === id
      );
      if (!section) return null;
      const Form = forms.find((f) => f.type === section.type);
      if (!Form) return null;
      return { Form, id };
    })
    .filter(Boolean); // Filtre les formulaires null

  return (
    <div className="page-sections-manager">
      {orderedForms.map(({ Form, id }, index) => (
        <div key={id} className="section-container">
          {showOrderButtons && (
            <div className="order-buttons">
              <button
                onClick={() => moveSection(index, "up")}
                disabled={index === 0}
              >
                <ArrowUp />
              </button>
              <button
                onClick={() => moveSection(index, "down")}
                disabled={index === orderedForms.length - 1}
              >
                <ArrowDown />
              </button>
            </div>
          )}
          <div className="section-content">
            <Form pageName={pageName} />
          </div>
        </div>
      ))}
    </div>
  );
};

export default PageSectionManager;
