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

const HeroBanner = () => {
  const [isInitialized, setIsInitialized] = useState(false);
  const [isStyleOpen, setIsStyleOpen] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const init = () => {
    if (!formData.value) formData.value = {};
    if (!formData.value["homePage"]) formData.value["homePage"] = {};
    if (!formData.value["homePage"]["heroBanner"])
      formData.value["homePage"]["heroBanner"] = {
        selectedStyle: window.wb_onboard_options.theme || "ace",
      };
    setIsInitialized(true);
  };

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

  if (!isInitialized) return null;

  const section = formData.value.homePage.heroBanner;
  if (!section) return null;

  const handleChange = (field, value) => {
    formData.value = {
      ...formData.value,
      homePage: {
        ...formData.value["homePage"],
        heroBanner: {
          ...formData.value["homePage"]["heroBanner"],
          [field]: value,
        },
      },
    };
  };

  // Theme data with optional image URLs
  const themes = [
    {
      id: "ace",
      name: "Ace",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/ace/preview-home-hero-banner.png",
    },
    {
      id: "accelerator",
      name: "Accelerator",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/accelerator/preview-home-hero-banner.png",
    },
    {
      id: "triumph",
      name: "Triumph",
      imageUrl:
        "https://themesondemand.b-cdn.net/MioCommerce/Olympus/styles/triumph/preview-home-hero-banner.png",
    },
  ];

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

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

  const handleValuePropositionChange = (id, value) => {
    const updatedPropositions = section.valuePropositions.map((prop) =>
      prop.id === id ? { ...prop, text: value } : prop
    );
    handleChange("valuePropositions", updatedPropositions);
  };

  const addValueProposition = () => {
    if (section.valuePropositions.length < 12) {
      const newProposition = { id: Date.now(), text: "" };

      handleChange("valuePropositions", [
        ...section.valuePropositions,
        newProposition,
      ]);
    }
  };

  const removeValueProposition = (id) => {
    const updatedPropositions = section.valuePropositions.filter(
      (prop) => prop.id !== id
    );
    handleChange("valuePropositions", updatedPropositions);
  };

  const moveValueProposition = (index, direction) => {
    const newPropositions = [...section.valuePropositions];
    if (direction === "up" && index > 0) {
      [newPropositions[index], newPropositions[index - 1]] = [
        newPropositions[index - 1],
        newPropositions[index],
      ];
    } else if (
      direction === "down" &&
      index < section.valuePropositions.length - 1
    ) {
      [newPropositions[index], newPropositions[index + 1]] = [
        newPropositions[index + 1],
        newPropositions[index],
      ];
    }
    handleChange("valuePropositions", newPropositions);
  };

  // Get all services from categories for the select
  const getServiceOptions = () => {
    const options = [];
    formData.value.categoriesServices?.forEach((category) => {
      category.services.forEach((service) => {
        options.push(`${category.name} - ${service.title}`);
      });
    });
    return options;
  };

  return (
    <div className="form-layout-container hero-banner-form">
      <div className="form-layout-header">
        <div className="form-layout-title">
          <h3>Home Hero Banner</h3>
          <p>
            This is the first section on the home page with your main title and
            image. This is the first thing customers will see when landing on
            your website.
          </p>
        </div>
        <button
          className="edit-section-button"
          onClick={() => setDrawerOpen(true)}
        >
          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>
      <WBDrawer
        isOpen={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        title="Edit Home Hero Banner"
        image={getPreviewImage()}
        previewSlug="/"
        previewTitle="Preview Home Page"
      >
        <div className="form-layout-content">
          {window.wb_onboard_options.theme != "accelerator" && (
            <ThemeSelect
              isOpen={isStyleOpen}
              onToggle={() => setIsStyleOpen(!isStyleOpen)}
              themes={themes}
              selectedTheme={section.selectedStyle}
              onThemeSelect={(themeId) =>
                handleChange("selectedStyle", themeId)
              }
            />
          )}

          <div className="hero-form">
            <div className="form-group">
              <label className="form-label">Main Image</label>
              <FilePicker
                value={section.heroImage}
                setValue={(value) => handleChange("heroImage", value)}
                label={{
                  choose: "Choose hero image",
                  change: "Change image",
                  current: "Current image",
                  cancel: "Cancel",
                  dragText: "Drag and drop your hero image here",
                  orText: "or",
                  uploading: "Uploading...",
                }}
              />
              <span className="input-details">
                This image is used as a background. Please provide a high
                resolution image (1920x1080) containing no text.
              </span>
            </div>

            <div className="form-group">
              <label className="form-label">Main Tagline</label>
              <input
                className="form-input"
                type="text"
                value={section.primaryTagline}
                onChange={(e) => {
                  handleChange("primaryTagline", e.target.value);
                }}
                placeholder="Enter your main tagline"
              />
            </div>

            <div className="form-group">
              <label className="form-label">Tagline subtitle</label>
              <input
                className="form-input"
                type="text"
                value={section.serviceTagline}
                onChange={(e) => {
                  handleChange("serviceTagline", e.target.value);
                }}
                placeholder="Enter your service tagline"
              />
            </div>
            {section.selectedStyle === "ace" && (
              <div className="form-group value-propositions">
                <label className="form-label">Value Propositions</label>
                {section.valuePropositions.map((prop, index) => (
                  <div key={prop.id} className="value-proposition-item">
                    <div className="value-proposition-controls">
                      {index > 0 && (
                        <button
                          onClick={() => moveValueProposition(index, "up")}
                        >
                          ↑
                        </button>
                      )}
                      {index < section.valuePropositions.length - 1 && (
                        <button
                          onClick={() => moveValueProposition(index, "down")}
                        >
                          ↓
                        </button>
                      )}
                    </div>
                    <input
                      className="form-input"
                      type="text"
                      value={prop.text}
                      onChange={(e) =>
                        handleValuePropositionChange(prop.id, e.target.value)
                      }
                      placeholder={`Value proposition ${index + 1}`}
                    />
                    {section.valuePropositions.length > 1 && (
                      <button
                        className="remove-proposition"
                        onClick={() => removeValueProposition(prop.id)}
                      >
                        ×
                      </button>
                    )}
                  </div>
                ))}
                {section.valuePropositions.length < 12 && (
                  <button
                    className="add-proposition-button form-button"
                    onClick={addValueProposition}
                  >
                    Add Value Proposition
                  </button>
                )}
              </div>
            )}

            {window.wb_onboard_options.variation == "premium" && (
              <div
                className="form-group price-card-section"
                style={{ borderTop: "1px solid var(--color-gray-light)" }}
              >
                <div className="section-header">
                  <div>
                    <label className="form-label">Price Card</label>

                    <span className="input-details">
                      The price card is a direct link to one of your services so
                      that people can quickly buy online.
                    </span>
                  </div>
                  {!isAdvancedThemeVariation() && (
                    <TODToggle
                      value={section.showPriceCard ?? false}
                      onChange={(value) => handleChange("showPriceCard", value)}
                      label="Show price card?"
                    />
                  )}
                  {isAdvancedThemeVariation() && (
                    <span style={{ fontSize: 12 }}>Premium only!</span>
                  )}
                </div>

                {section.showPriceCard && (
                  <>
                    <div className="form-group">
                      <label className="form-label">Price Card Title</label>
                      <input
                        className="form-input"
                        type="text"
                        value={section.priceCardTitle}
                        onChange={(e) => {
                          handleChange("priceCardTitle", e.target.value);
                        }}
                        placeholder="Enter price card title"
                      />
                    </div>

                    <div className="form-group">
                      <label className="form-label">
                        Price Card Description
                      </label>
                      <textarea
                        className="form-input"
                        value={section.priceCardDescription}
                        onChange={(e) => {
                          handleChange("priceCardDescription", e.target.value);
                        }}
                        placeholder="Enter price card description"
                      />
                    </div>

                    <div className="form-group">
                      <label className="form-label">Price Card Link Text</label>
                      <input
                        className="form-input"
                        type="text"
                        value={section.priceCardLinkText}
                        onChange={(e) => {
                          handleChange("priceCardLinkText", e.target.value);
                        }}
                        placeholder="Enter link text"
                      />
                    </div>

                    <div className="form-group">
                      <label className="form-label">Select Service</label>
                      <select
                        className="form-input"
                        value={section.selectedService}
                        onChange={(e) => {
                          handleChange("selectedService", e.target.value);
                        }}
                      >
                        <option value="">Select a service</option>
                        {getServiceOptions().map((option, index) => (
                          <option key={index} value={option}>
                            {option}
                          </option>
                        ))}
                      </select>
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
        </div>
      </WBDrawer>
    </div>
  );
};

export default HeroBanner;
