import React, { useState, useEffect } from "react";
import Task from "./components/task/Task";
import SiteInfo from "./components/site-info/SiteInfo";
import DomainForm from "./components/domain-form/DomainForm";
import "./LiveApp.css";
import HelpButton from "./components/help-button/HelpButton";

// Constantes pour les IDs des tâches
const TASK_IDS = {
  DOMAIN_SETUP: "domain_setup",
  PLUGINS_ACTIVATION: "plugins_activation",
  CITY_PAGES: "city_pages",
  BOOKING_PAGES: "booking_pages",
};

const LiveApp = () => {
  // Get data from the localized script
  const { site_url, dashboard_url, onboard_options, tasks } =
    window.live_app_data || {};

  // Initialiser avec les données des tâches si disponibles
  const initialTaskStates = tasks?.data?.data || {
    [TASK_IDS.DOMAIN_SETUP]: false,
    [TASK_IDS.PLUGINS_ACTIVATION]: false,
    [TASK_IDS.CITY_PAGES]: false,
    [TASK_IDS.BOOKING_PAGES]: false,
  };

  const [taskStates, setTaskStates] = useState(initialTaskStates);

  // Réorganiser les tâches dans le DOM
  const reorderTasks = () => {
    const tasksContainer = document.querySelector(".tasks-list");
    if (!tasksContainer) return;

    const tasks = Array.from(tasksContainer.children);
    const completedTasks = tasks.filter((task) =>
      task.querySelector(".task-checkbox.done")
    );
    const incompleteTasks = tasks.filter(
      (task) => !task.querySelector(".task-checkbox.done")
    );

    // Trier les tâches incomplètes selon leur ordre original
    incompleteTasks.sort((a, b) => {
      return parseInt(a.dataset.order) - parseInt(b.dataset.order);
    });

    // Trier les tâches complétées selon leur ordre original
    completedTasks.sort((a, b) => {
      return parseInt(a.dataset.order) - parseInt(b.dataset.order);
    });

    // Vider le conteneur
    tasksContainer.innerHTML = "";

    // Ajouter d'abord les tâches incomplètes
    incompleteTasks.forEach((task) => tasksContainer.appendChild(task));

    // Puis les tâches complétées
    completedTasks.forEach((task) => tasksContainer.appendChild(task));
  };

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

  const handleTaskChange = async (taskId, status) => {
    // Optimistic update
    setTaskStates((prev) => ({
      ...prev,
      [taskId]: status,
    }));

    try {
      const response = await fetch(
        `${site_url}/wp-json/wb-onboard/v1/tasks/status`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            task_id: taskId,
            status: status,
          }),
        }
      );

      const result = await response.json();

      if (!result.success) {
        // Rollback en cas d'erreur
        setTaskStates((prev) => ({
          ...prev,
          [taskId]: !status,
        }));
        console.error("Error updating task:", result);
      } else {
        // Réorganiser les tâches après une mise à jour réussie
        setTimeout(reorderTasks, 50); // Petit délai pour laisser le DOM se mettre à jour
      }
    } catch (error) {
      // Rollback en cas d'erreur réseau
      setTaskStates((prev) => ({
        ...prev,
        [taskId]: !status,
      }));
      console.error("Error updating task:", error);
    }
  };

  return (
    <div className="live-app">
      <SiteInfo siteUrl={site_url} dashboardUrl={dashboard_url} />

      <div className="tasks-section">
        <HelpButton />

        <h2>Next steps to boost your website</h2>
        <p className="tasks-intro">
          Your new website is now live on{" "}
          <a
            class="current-url"
            href={site_url}
            target="_blank"
            style={{ color: "inherit" }}
          >
            <span>{site_url}</span>
          </a>
          ! Complete the optional steps below to go live on your own business
          domain and install free E-commerce plugins and our advanced booking
          technology to engage and convert visitors into buyers.
        </p>

        {/* <div className="tasks-tip">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
            <path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z" />
          </svg>
          <span>
            Click the checkbox next to each task to track your progress
          </span>
        </div> */}

        <div className="tasks-list">
          <div className="tasks-checkbox-label">
            <span>Mark as completed</span>
          </div>

          <Task
            title="Connect Your Custom Domain"
            subtitle="Make your website accessible through your own custom URL"
            initialDone={taskStates[TASK_IDS.DOMAIN_SETUP]}
            onStatusChange={(status) =>
              handleTaskChange(TASK_IDS.DOMAIN_SETUP, status)
            }
            order={1}
          >
            <DomainForm />
          </Task>

          <Task
            title="Install MioCommerce’s Free Plugins and Turbo Charge your website & Business performance"
            subtitle="Our Free Website Plugin are Free for to use forever - no paid subscription is required"
            initialDone={taskStates[TASK_IDS.PLUGINS_ACTIVATION]}
            onStatusChange={(status) =>
              handleTaskChange(TASK_IDS.PLUGINS_ACTIVATION, status)
            }
            order={2}
          >
            <div style={{ marginTop: "1rem" }}>
              {onboard_options?.website_dashboard_url ? (
                <a
                  href={onboard_options.website_dashboard_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="wb-button primary"
                >
                  Get your FREE e-commerce Plugins
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 512 512"
                    width="14"
                    height="14"
                    style={{ marginLeft: "0.5rem" }}
                  >
                    <path
                      fill="currentColor"
                      d="M320 0c-17.7 0-32 14.3-32 32s14.3 32 32 32h82.7L201.4 265.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L448 109.3V192c0 17.7 14.3 32 32 32s32-14.3 32-32V32c0-17.7-14.3-32-32-32H320zM80 32C35.8 32 0 67.8 0 112V432c0 44.2 35.8 80 80 80H400c44.2 0 80-35.8 80-80V320c0-17.7-14.3-32-32-32s-32 14.3-32 32V432c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V112c0-8.8 7.2-16 16-16H192c17.7 0 32-14.3 32-32s-14.3-32-32-32H80z"
                    />
                  </svg>
                </a>
              ) : (
                <div className="notice-box">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 512 512"
                    width="16"
                    height="16"
                  >
                    <path
                      fill="currentColor"
                      d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"
                    />
                  </svg>
                  <span>
                    The plugin activation link will be available once your
                    website is ready.
                  </span>
                </div>
              )}
            </div>
          </Task>

          <Task
            title="Create and Embed Advanced Booking Pages to your website"
            subtitle="Instantly Convert website visitors into bookings and revenue"
            initialDone={taskStates[TASK_IDS.BOOKING_PAGES]}
            onStatusChange={(status) =>
              handleTaskChange(TASK_IDS.BOOKING_PAGES, status)
            }
            order={3}
          >
            <p>
              For each service you sell, create and embed any one of
              MioCommerce’s customizable advanced booking pages technology to
              instantly engage visitors and convert them into bookings and
              revenue. With a simple click you can also add them to any email,
              chat, SMS, Facebook messenger, Instagram, etc message sent to
              prospects and customers when using your Multi-Channel Inbox. To
              learn more click on the links below.
            </p>
            <ol>
              <li>
                <a
                  href="https://support.miocommerce.com/en/articles/4995973-live-pricing-real-time-booking-page"
                  target="_blank"
                >
                  Live Pricing and Real-Time booking pages
                </a>
              </li>
              <li>
                <a
                  href="https://support.miocommerce.com/en/articles/8283530-how-to-create-an-interactive-quote-iq"
                  target="_blank"
                >
                  Interactive Quote page
                </a>
              </li>
              <li>
                <a
                  href="https://support.miocommerce.com/en/articles/11165067-how-to-create-a-service-request"
                  target="_blank"
                >
                  Service Request
                </a>
              </li>
              <li>
                <a
                  href="https://support.miocommerce.com/en/articles/11164912-service-request-pages-v-s-interactive-quote-pages-v-s-live-pricing-real-time-booking-pages"
                  target="_blank"
                >
                  Overview - Use Cases for each
                </a>
              </li>
            </ol>
            <div style={{ position: "relative", height: 50, width: 155 }}>
              <HelpButton />
            </div>
          </Task>
        </div>
      </div>
    </div>
  );
};

export default LiveApp;
