import React, { useState, useEffect, useRef } from "react";
import { formData } from "../../../../features/context/TOD.FormulaireData";
import { ArrowUp, ArrowDown } from "../../../../components/icons/arrow";
import ServicesItem from "../sections/services/ServicesItem";
import { generatePreview } from "../../../../features/navigation/components/TOD.Navigation.js";

const TrashIcon = () => (
  <svg
    width="11"
    height="12"
    viewBox="0 0 11 12"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <g clipPath="url(#clip0_47_278)">
      <path
        d="M4.34844 1.125H6.64911C6.7154 1.125 6.77679 1.15547 6.81362 1.20937L7.28013 1.875H3.71987L4.18638 1.20937C4.22321 1.15781 4.2846 1.125 4.35089 1.125H4.34844ZM8.69688 1.875L7.79576 0.583594C7.5404 0.220312 7.11071 0 6.65156 0H4.34844C3.88929 0 3.4596 0.220312 3.20424 0.583594L2.30313 1.875H1.96674H0.785714H0.589286C0.262723 1.875 0 2.12578 0 2.4375C0 2.74922 0.262723 3 0.589286 3H0.874107L1.46339 10.6102C1.52478 11.393 2.20737 12 3.02991 12H7.96763C8.79018 12 9.47277 11.393 9.53415 10.6102L10.1259 3H10.4107C10.7373 3 11 2.74922 11 2.4375C11 2.12578 10.7373 1.875 10.4107 1.875H10.2143H9.03326H8.69688ZM8.94487 3L8.36049 10.5281C8.34576 10.725 8.17388 10.875 7.96763 10.875H3.02991C2.82366 10.875 2.65424 10.7227 2.63705 10.5281L2.05513 3H8.94487Z"
        fill="black"
      />
    </g>
    <defs>
      <clipPath id="clip0_47_278">
        <rect width="11" height="12" fill="white" />
      </clipPath>
    </defs>
  </svg>
);

const Services = () => {
  const [categories, setCategories] = useState(
    formData.value.categoriesServices || []
  );
  const [expandedServices, setExpandedServices] = useState({});
  const [editingCategory, setEditingCategory] = useState(null);
  const [openCategoryPopovers, setOpenCategoryPopovers] = useState([]);
  const openCategoryPopoversRef = useRef(openCategoryPopovers);
  openCategoryPopoversRef.current = openCategoryPopovers;

  useEffect(() => {
    formData.value = {
      ...formData.value,
      categoriesServices: categories,
    };
  }, [categories]);

  const addCategory = () => {
    setCategories([
      ...categories,
      {
        name: "New category",
        ctaText: "Book & Buy Now",
        services: [],
      },
    ]);
  };

  const isAdvancedThemeVariation = () => {
    if (
      window.wb_onboard_options.variation &&
      window.wb_onboard_options.variation == "advanced"
    )
      return true;
    return false;
  };

  const updateCategoryName = (index, name) => {
    const newCategories = [...categories];
    newCategories[index].name = name;
    setCategories(newCategories);
  };

  const deleteCategory = (index) => {
    const newCategories = categories.filter((_, i) => i !== index);
    setCategories(newCategories);
  };

  const editCategory = (index) => {
    setEditingCategory(index);
  };

  const handleCategoryNameChange = (index, name) => {
    updateCategoryName(index, name);
    setEditingCategory(null);
  };

  const handleCategoryKeyDown = (e, index) => {
    if (e.key === "Enter") {
      handleCategoryNameChange(index, e.target.value);
    }
  };

  const handleCategoryBlur = (e, index) => {
    handleCategoryNameChange(index, e.target.value);
  };

  const moveCategoryUp = (index) => {
    if (index === 0) return;
    const newCategories = [...categories];
    [newCategories[index], newCategories[index - 1]] = [
      newCategories[index - 1],
      newCategories[index],
    ];
    setCategories(newCategories);
  };

  const moveCategoryDown = (index) => {
    if (index === categories.length - 1) return;
    const newCategories = [...categories];
    [newCategories[index], newCategories[index + 1]] = [
      newCategories[index + 1],
      newCategories[index],
    ];
    setCategories(newCategories);
  };

  const addService = (categoryIndex) => {
    const newCategories = [...categories];
    newCategories[categoryIndex].services.push({
      title: "New service",
      description: "<p>Enter your description here</p>",
      ctaText: "Book & Buy Now",
      images: [],
      mainImage: {
        url: "",
        attachment_id: null,
      },
      bookingPageScript: "",
    });
    setCategories(newCategories);
    toggleService(
      categoryIndex,
      newCategories[categoryIndex].services.length - 1
    );
  };

  const updateService = (categoryIndex, serviceIndex, field, value) => {
    const newCategories = [...categories];
    newCategories[categoryIndex].services[serviceIndex][field] = value;
    setCategories(newCategories);
  };

  const deleteService = (categoryIndex, serviceIndex) => {
    const newCategories = [...categories];
    newCategories[categoryIndex].services = newCategories[
      categoryIndex
    ].services.filter((_, i) => i !== serviceIndex);
    setCategories(newCategories);
  };

  const moveServiceUp = (categoryIndex, serviceIndex) => {
    if (serviceIndex === 0) return;
    const newCategories = [...categories];
    const services = newCategories[categoryIndex].services;
    [services[serviceIndex], services[serviceIndex - 1]] = [
      services[serviceIndex - 1],
      services[serviceIndex],
    ];
    setCategories(newCategories);
  };

  const moveServiceDown = (categoryIndex, serviceIndex) => {
    const newCategories = [...categories];
    const services = newCategories[categoryIndex].services;
    if (serviceIndex === services.length - 1) return;
    [services[serviceIndex], services[serviceIndex + 1]] = [
      services[serviceIndex + 1],
      services[serviceIndex],
    ];
    setCategories(newCategories);
  };

  const toggleService = (categoryIndex, serviceIndex) => {
    const key = `${categoryIndex}-${serviceIndex}`;
    setExpandedServices((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const addOpenCategoryPopover = (categoryIndex) => {
    if (!openCategoryPopovers.includes(categoryIndex)) {
      setOpenCategoryPopovers([...openCategoryPopovers, categoryIndex]);
      setTimeout(() => removeOpenCategoryPopover(categoryIndex), 3000);
    }
  };

  const removeOpenCategoryPopover = (categoryIndex) => {
    if (openCategoryPopoversRef.current.includes(categoryIndex)) {
      const tempOpenCategoryPopovers = openCategoryPopoversRef.current.filter(
        (e) => e !== categoryIndex
      );
      setOpenCategoryPopovers(tempOpenCategoryPopovers);
    }
  };

  return (
    <div className="form-container" style={{ maxWidth: 1200 }}>
      <div className="service-handler">
        <div>
          <h2>2. Create Categories and Service pages</h2>
          <p>
            Create your service pages by entering the services you offer below.
            You need to group services by categories. For example, all your
            services could fall under a single category called "Our Services",
            or you could split your services between "Residential Services" and
            "Commercial Services" To add categories scroll the very bottom of
            this page.
          </p>
        </div>
        {categories.map((category, categoryIndex) => (
          <div className="service-handler-container">
            <div className="order-buttons">
              <button
                onClick={() => moveCategoryUp(categoryIndex)}
                disabled={categoryIndex === 0}
              >
                <ArrowUp />
              </button>
              <button
                onClick={() => moveCategoryDown(categoryIndex)}
                disabled={categoryIndex === categories.length - 1}
              >
                <ArrowDown />
              </button>
            </div>
            <div key={categoryIndex} className="category-container">
              <div className="category-header">
                <div className="category-content">
                  {editingCategory === categoryIndex ? (
                    <>
                      <input
                        type="text"
                        value={category.name}
                        onChange={(e) =>
                          updateCategoryName(categoryIndex, e.target.value)
                        }
                        onKeyDown={(e) =>
                          handleCategoryKeyDown(e, categoryIndex)
                        }
                        onBlur={(e) => handleCategoryBlur(e, categoryIndex)}
                        placeholder="Category name"
                        autoFocus
                      />
                      <span style={{ cursor: "pointer", fontSize: "14px" }}>
                        Save
                      </span>
                    </>
                  ) : (
                    <>
                      <div className="category-title">
                        <h3>Category: {category.name}</h3>
                        <div
                          className="edit-section-button"
                          onClick={() => editCategory(categoryIndex)}
                        >
                          Edit category name
                          <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" />
                          </svg>
                        </div>
                        <a
                          className="wb-form-btn preview-btn invert active"
                          onClick={() =>
                            generatePreview(
                              category.name
                                ? "/" +
                                    category.name
                                      .toLowerCase()
                                      .replace(/[^\w ]+/g, "")
                                      .replace(/ +/g, "-")
                                : ""
                            )
                          }
                        >
                          Preview category
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            height="1em"
                            viewBox="0 0 576 512"
                          >
                            <path d="M129.1 361.4C93.6 327.2 67.7 286.9 52.5 256c15.1-30.9 41-71.2 76.6-105.4C171.8 109.5 224.9 80 288 80s116.2 29.5 158.9 70.6c35.6 34.3 61.5 74.5 76.6 105.4c-15.1 30.9-41 71.2-76.6 105.4C404.2 402.5 351.1 432 288 432s-116.2-29.5-158.9-70.6zM288 480c158.4 0 258-149.3 288-224C546 181.3 446.4 32 288 32S30 181.3 0 256c30 74.7 129.6 224 288 224zm0-144c-44.2 0-80-35.8-80-80c0-5.4 .5-10.6 1.5-15.7L288 256l-15.7-78.5c5.1-1 10.3-1.5 15.7-1.5c44.2 0 80 35.8 80 80s-35.8 80-80 80zM160 256c0 70.7 57.3 128 128 128s128-57.3 128-128s-57.3-128-128-128c-8.6 0-17 .8-25.1 2.5c-50.3 10-90 49.5-100.3 99.7l-.1 .7c-1.6 8.1-2.5 16.5-2.5 25.1z" />
                          </svg>
                        </a>
                      </div>
                      <div className="delete-button-popover">
                        {openCategoryPopovers.includes(categoryIndex) && (
                          <div className="delete-button-popover-content">
                            Delete category and all services inside?
                            <a
                              onClick={() => {
                                removeOpenCategoryPopover(categoryIndex);
                                deleteCategory(categoryIndex);
                              }}
                            >
                              Yes
                            </a>
                          </div>
                        )}
                        <button
                          onClick={() => addOpenCategoryPopover(categoryIndex)}
                          className="delete-button"
                          title="Delete category"
                        >
                          <TrashIcon />
                        </button>
                      </div>
                    </>
                  )}
                </div>
              </div>

              <div className="form-layout-content">
                <p>
                  Each category will have a dedicated “category title” page with
                  all the respective services in that category showcased on the
                  category page.
                </p>
              </div>

              <div className="services-list">
                <div>
                  <h4>Services under the "{category.name}" category</h4>
                  <p>
                    Edit and/or Create the title and description for each of the
                    service offerings you want to sell/market to your customers.
                    Each Service will have a dedicated “service page”. You can
                    list the services in the order you wish for them to appear
                    on the home page as well as in the dropdown in the main
                    menu.
                  </p>
                </div>
                {category.services.map((service, serviceIndex) => {
                  const isExpanded =
                    expandedServices[`${categoryIndex}-${serviceIndex}`];
                  return (
                    <ServicesItem
                      moveServiceUp={moveServiceUp}
                      moveServiceDown={moveServiceDown}
                      categoryIndex={categoryIndex}
                      serviceIndex={serviceIndex}
                      category={category}
                      service={service}
                      updateService={updateService}
                      deleteService={deleteService}
                    />
                  );
                })}
                <div className="wb-input-repeater-controls">
                  {category.services.length < 20 && (
                    <button
                      onClick={() => addService(categoryIndex)}
                      className="wb-input-repeater-add-row"
                    >
                      Add service
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        viewBox="0 0 448 512"
                        height="1em"
                      >
                        <path d="M240 64c0-8.8-7.2-16-16-16s-16 7.2-16 16V240H32c-8.8 0-16 7.2-16 16s7.2 16 16 16H208V448c0 8.8 7.2 16 16 16s16-7.2 16-16V272H416c8.8 0 16-7.2 16-16s-7.2-16-16-16H240V64z" />
                      </svg>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}
        {categories.length < 10 && !isAdvancedThemeVariation() && (
          <button onClick={addCategory} className="wb-input-repeater-add-row">
            Add category
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 448 512"
              height="1em"
            >
              <path d="M240 64c0-8.8-7.2-16-16-16s-16 7.2-16 16V240H32c-8.8 0-16 7.2-16 16s7.2 16 16 16H208V448c0 8.8 7.2 16 16 16s16-7.2 16-16V272H416c8.8 0 16-7.2 16-16s-7.2-16-16-16H240V64z" />
            </svg>
          </button>
        )}
      </div>
    </div>
  );
};

export default Services;
