import React, { useEffect, useState } from "react";
import {
  formData,
  formulaireUtils,
} from "../../../../../features/context/TOD.FormulaireData";
import WBRepeater from "../../../../../components/inputs/repeater/WBRepeater";
import WBRepeaterRow from "../../../../../components/inputs/repeater/WBRepeaterRow";
import TODToggle from "../../../../../components/inputs/toggle/TOD.Toggle";
import ThemeSelect from "../../../../../components/inputs/theme-select/TOD.ThemeSelect";
import WBDrawer from "../../../../../components/WBDrawer";
import "./bookingStep.css";

import IconPicker from "../../../../../components/inputs/icon-picker/TOD.IconPicker";
import WBSpacer from "../../../../../components/WBSpacer";

const BookingStep = ({ pageName }) => {
  const [isStyleOpen, setIsStyleOpen] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const themes = [
    {
      id: "ace",
      name: "Ace",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/ace/how-it-works.png",
    },
    {
      id: "accelerator",
      name: "Accelerator",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/accelerator/how-it-works.png",
    },
    {
      id: "triumph",
      name: "Triumph",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/triumph/how-it-works.png",
    },
  ];

  const getPreviewImage = () => {
    const theme = window.wb_onboard_options.theme || "ace";
    if (theme == "ace")
      return "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/ace/how-it-works.png";
    if (theme == "accelerator")
      return "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/accelerator/how-it-works.png";
    if (theme == "triumph")
      return "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/triumph/how-it-works.png";
  };

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

  const getData = () => {
    return (
      formData.value[pageName].sections.find(
        (section) => section.type === BookingStep.type
      )?.data || { title: "", description: "", steps: [], selectedStyle: "ace" }
    );
  };

  const addStep = () => {
    const currentData = getData();
    handleChange("steps", [
      ...currentData.steps,
      { icon: "", title: "", stepDescription: "" },
    ]);
  };

  const updateStep = (index, field, value) => {
    const currentData = getData();
    const newSteps = [...currentData.steps];
    newSteps[index] = { ...newSteps[index], [field]: value };
    handleChange("steps", newSteps);
  };

  const deleteStep = (index) => {
    const currentData = getData();
    const newSteps = currentData.steps.filter((_, i) => i !== index);
    handleChange("steps", newSteps);
  };

  const reorderStep = (index, direction) => {
    const currentData = getData();
    const newSteps = [...currentData.steps];
    if (direction === "up" && index > 0) {
      [newSteps[index], newSteps[index - 1]] = [
        newSteps[index - 1],
        newSteps[index],
      ];
    } else if (direction === "down" && index < newSteps.length - 1) {
      [newSteps[index], newSteps[index + 1]] = [
        newSteps[index + 1],
        newSteps[index],
      ];
    }
    handleChange("steps", newSteps);
  };

  const data = getData();

  return (
    <div
      className={`form-layout-container booking-step-form ${
        !data.isVisible ? "section-hidden" : ""
      }`}
    >
      <div className="form-layout-header">
        <div className="form-layout-title">
          <h3>How It Works Section</h3>
          <p>
            Explain the process of working with your company. What happens when
            a customer books a service?
          </p>
        </div>
        <div className="form-layout-options">
          <TODToggle
            value={data.isVisible ?? true}
            onChange={(value) => handleChange("isVisible", value)}
            label="Show this section?"
          />
          <button
            className={`edit-section-button ${
              !data.isVisible ? "disabled" : ""
            }`}
            onClick={() => setDrawerOpen(true)}
            disabled={!data.isVisible}
          >
            Edit Section
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
              <path d="M36.4 360.9L13.4 439 1 481.2C-1.5 489.7 .8 498.8 7 505s15.3 8.5 23.7 6.1L73 498.6l78.1-23c12.4-3.6 23.7-9.9 33.4-18.4c1.4-1.2 2.7-2.5 4-3.8L492.7 149.3c21.9-21.9 24.6-55.6 8.2-80.5c-2.3-3.5-5.1-6.9-8.2-10L453.3 19.3c-25-25-65.5-25-90.5 0L58.6 323.5c-10.4 10.4-18 23.3-22.2 37.4zm46 13.5c1.7-5.6 4.5-10.8 8.4-15.2c.6-.6 1.1-1.2 1.7-1.8L321 129 383 191 154.6 419.5c-4.7 4.7-10.6 8.2-17 10.1l-23.4 6.9L59.4 452.6l16.1-54.8 6.9-23.4z"></path>
            </svg>
          </button>
        </div>
      </div>

      <WBDrawer
        isOpen={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        title="Edit How It Works Section"
        image={getPreviewImage()}
        previewSlug="/"
        previewTitle="Preview Home Page"
      >
        <div className="form-layout-content">
          <div className="form-group style-options">
            <ThemeSelect
              isOpen={isStyleOpen}
              onToggle={() => setIsStyleOpen(!isStyleOpen)}
              themes={themes}
              selectedTheme={data.selectedStyle}
              onThemeSelect={(themeId) =>
                handleChange("selectedStyle", themeId)
              }
            />
          </div>

          <div className="form-group">
            <label className="form-label">Section Title</label>
            <input
              className="form-input"
              type="text"
              value={data.title}
              onChange={(e) => handleChange("title", e.target.value)}
              placeholder="Enter section title"
            />
          </div>
          <WBSpacer />
          <div className="form-group">
            <label className="form-label">Section Description</label>
            <textarea
              className="form-input"
              value={data.description}
              onChange={(e) => handleChange("description", e.target.value)}
              placeholder="Enter section description"
            />
          </div>
          <WBSpacer />

          <div className="form-group">
            <label className="form-label">How It Works Steps</label>
            <WBRepeater addClick={addStep}>
              {data.steps.map((step, index) => (
                <WBRepeaterRow
                  key={index}
                  index={index}
                  onDelete={deleteStep}
                  onChangeOrder={reorderStep}
                  title={step.title || `Step ${index + 1}`}
                  isAccordion={true}
                >
                  <div className="form-group">
                    <div className="form-group-row">
                      <IconPicker
                        label="Select Icon"
                        value={step.icon}
                        onChange={(value) => updateStep(index, "icon", value)}
                      />
                    </div>
                    <div className="form-group-row">
                      <label className="form-label">Step Title</label>
                      <input
                        className="form-input"
                        type="text"
                        value={step.title}
                        onChange={(e) =>
                          updateStep(index, "title", e.target.value)
                        }
                        placeholder="Step Title"
                      />
                    </div>
                    <div className="form-group-row">
                      <label className="form-label">Step Description</label>
                      <textarea
                        className="form-input"
                        value={step.stepDescription}
                        onChange={(e) =>
                          updateStep(index, "stepDescription", e.target.value)
                        }
                        placeholder="Step Description"
                      />
                    </div>
                  </div>
                </WBRepeaterRow>
              ))}
            </WBRepeater>
          </div>
        </div>
      </WBDrawer>
    </div>
  );
};

BookingStep.type = "booking-step";

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

  if (!exists) {
    const id = formData.value[pageName].sections.length;
    formData.value[pageName].sections.push({
      id: id,
      type: BookingStep.type,
      data: {
        title: "",
        description: "",
        steps: [],
        isVisible: true,
        selectedStyle: window.wb_onboard_options.theme || "ace",
      },
    });
    formData.value[pageName].sectionsOrder.push(id);
  }
};

export default BookingStep;
