import { useState } from "react";
import {
  formData,
  formulaireUtils,
} from "../../../../../features/context/TOD.FormulaireData";
import TODToggleText from "../../../../../components/inputs/toggle-text/TOD.ToggleText";
import "./BookingScriptSection.css";
import { Step_n } from "../../../../../App.js";

const BookingScriptSection = ({ pageName }) => {
  const handleChange = (field, value) => {
    formulaireUtils.handleChange(
      field,
      value,
      pageName,
      BookingScriptSection.type
    );
  };

  const getSection = () => {
    return formulaireUtils.getSection(pageName, BookingScriptSection.type);
  };

  const section = getSection();
  if (!section) return null;

  const ensureAllServicesExist = () => {
    // S'assurer que section.data.services est un tableau
    if (!Array.isArray(section.data.services)) {
      section.data.services = [];
    }

    const currentServices = section.data.services;
    const updatedServices = [...currentServices];
    let hasChanges = false;

    formData.value.categoriesServices?.forEach((category) => {
      category.services.forEach((service) => {
        const serviceKey = `${category.name} %% ${service.title}`;
        if (!currentServices.find((s) => s.name === serviceKey)) {
          updatedServices.push({
            name: serviceKey,
            type: "contact",
            script: null,
          });
          hasChanges = true;
        }
      });
    });

    if (hasChanges) {
      handleChange("services", updatedServices);
    }
  };

  ensureAllServicesExist();

  const handleTypeChange = (categoryName, serviceTitle, scriptType) => {
    const serviceKey = `${categoryName} %% ${serviceTitle}`;
    const currentService = section.data.services.find(
      (service) => service.name === serviceKey
    );

    const updatedServices = section.data.services.map((service) =>
      service.name === serviceKey
        ? {
            ...service,
            type: scriptType,
            script: currentService?.script || "",
          }
        : service
    );

    handleChange("services", updatedServices);
  };

  const handleScriptChange = (categoryName, serviceTitle, scriptContent) => {
    const serviceKey = `${categoryName} %% ${serviceTitle}`;

    const updatedServices = section.data.services.map((service) =>
      service.name === serviceKey
        ? {
            ...service,
            script: scriptContent,
          }
        : service
    );

    handleChange("services", updatedServices);
  };

  const scriptOptions = [
    { value: "contact", label: "  Install Contact Us Page  " },
    { value: "custom", label: "Use Advanced Booking Script" },
  ];

  return (
    <div className="booking-script-section">
      <div className="form-layout-content">
        <p>For every service below, select one of the two options:</p>
        <ol style={{ fontSize: 13 }}>
          <li>
            <strong>
              Install a “ Contact Us” page (as a temporary default page)
            </strong>
            : You can always add / install any of the 3 advanced booking page
            types later.<br></br>Your “Contact Us” page is auto created in
            MioCommerce when you set-up your account. It will automatically be
            added to this service offering for online website visitors to fill.
            Visitor who completed the Contact Us page will appear as prospects
            in your account. You will also receive an email notification to
            inform you they reached out.{" "}
          </li>
          <li>
            <strong>Install Advanced Booking Script</strong>: when selected, you
            will be guided to provide the script for either the i) Service
            Request Page, or ii) custom ‘Live Pricing and Real-Time Booking
            Page’ or iii) ‘Interactive Quoting Page’ you created for that
            specific service. Website visitors will then be able to: i) schedule
            a call-back, onsite estimate or video conference, or ii) instantly
            book and buy your services or iii) submit a request for an
            interactive quote.
          </li>
        </ol>
        {formData.value.categoriesServices?.map((category, index) => (
          <div key={index} className="service-category">
            <h4>{category.name}</h4>
            {category.services.map((service, serviceIndex) => {
              const serviceKey = `${category.name} %% ${service.title}`;
              const savedScript = section.data.services?.find(
                (s) => s.name === serviceKey
              );
              return (
                <div
                  key={serviceIndex}
                  className="service-item booking-scripts"
                >
                  <div className="service-info">
                    <span className="service-title">{service.title}</span>
                    <TODToggleText
                      options={scriptOptions}
                      value={savedScript?.type || "contact"}
                      onChange={(value) =>
                        handleTypeChange(category.name, service.title, value)
                      }
                    />
                  </div>
                  <div className="script-config">
                    {savedScript?.type === "custom" && (
                      <div className="custom-script-input">
                        <textarea
                          placeholder="Paste the script for the respective advanced booking page"
                          value={savedScript.script || ""}
                          onChange={(e) =>
                            handleScriptChange(
                              category.name,
                              service.title,
                              e.target.value
                            )
                          }
                        />
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        ))}
        <button
          class="edit-section-button"
          style={{ fontSize: 16, marginRight: "auto", marginBottom: 30 }}
          onClick={() => {
            Step_n.value = Step_n.value + 1;
            window.scrollTo({ top: 0, behavior: "smooth" });
          }}
        >
          Go live with my website
        </button>
      </div>
    </div>
  );
};

BookingScriptSection.type = "bookingScript";

BookingScriptSection.init = (pageName) => {
  const exists = formData.value[pageName].sections.some(
    (section) => section.type === BookingScriptSection.type
  );

  if (!exists) {
    const id = formData.value[pageName].sections.length;

    // Initialiser tous les services avec le nouveau format
    const initialServices = [];
    formData.value.categoriesServices?.forEach((category) => {
      category.services.forEach((service) => {
        initialServices.push({
          name: `${category.name} %% ${service.title}`,
          type: "contact",
          script: null,
        });
      });
    });

    formData.value[pageName].sections.push({
      id,
      type: BookingScriptSection.type,
      data: {
        services: initialServices,
      },
    });
    formData.value[pageName].sectionsOrder.push(id);
  }
};

export default BookingScriptSection;
