import { filterFeaturesBasedOncurrentProject } from "@lib/_common/util";
import { SURVEY_FEATURES } from "@lib/_common/util/surveyFeatures";
import {
  scrollToFirstRequiredQuestion,
  submitCheckAndSaveWork,
  submitSaveWork,
} from "@lib/_common/util/surveyUtil";
import { TSurveyFeature } from "@lib/_common/util/types";
import { addStyles } from "@lib/setupRoot";
import { For, Show, createSignal, onMount } from "solid-js";
import floatingActionBarStyles from "./FloatingActionBar.css?inline";

export function FloatingActionBar() {
  const [isCurrentlyFilling, setIsCurrentlyFilling] = createSignal(false);
  const [isFillError, setIsFillError] = createSignal(false);
  const [errorMessages, setErrorMessages] = createSignal<string[]>([]);

  const surveyFeatures = filterFeaturesBasedOncurrentProject(SURVEY_FEATURES);

  function handleFeatureClick(feature: TSurveyFeature) {
    console.log(`Feature clicked: ${feature.featureName}`);

    setIsCurrentlyFilling(true);
    setIsFillError(false);

    feature
      .callback()
      .then(() => {
        console.log(`Feature '${feature.featureName}' executed successfully.`);
        setIsFillError(false);
      })
      .catch((error) => {
        console.error(`Error executing feature '${feature.featureName}':`, error);
        setIsFillError(true);
      })
      .finally(() => {
        setIsCurrentlyFilling(false);
      });
  }

  /**
   * Checks if the given date string is within the current week.
   * @param dateString The date string to check, example: `8/7/2025`
   * @returns True if the date is within this week, false otherwise.
   */
  function isDateWithinThisWeek(dateString: string): boolean {
    const date = new Date(dateString);
    const now = new Date();

    // get start of week (Sunday)
    const startOfWeek = new Date(now);
    startOfWeek.setDate(now.getDate() - now.getDay());
    startOfWeek.setHours(0, 0, 0, 0);

    // get end of week (Saturday)
    const endOfWeek = new Date(now);
    endOfWeek.setDate(now.getDate() + (6 - now.getDay()));
    endOfWeek.setHours(23, 59, 59, 999);

    return date >= startOfWeek && date <= endOfWeek;
  }

  onMount(() => {
    addStyles(floatingActionBarStyles);
    console.log("Mounting Floating App Action Bar");

    const serviceDateElement = document.querySelector<HTMLInputElement>(
      "[id$='_rmsChangeDatePicker_textboxDate']"
    );
    if (serviceDateElement === null) {
      console.error("Service date element not found.");
      setErrorMessages((prev) => [...prev, "Service date element not found."]);
      return;
    }

    if (!isDateWithinThisWeek(serviceDateElement.value)) {
      setErrorMessages((prev) => [...prev, "Service date must be within this week."]);
    }
  });

  return (
    <div id="mm-actions" style={"max-width: 230px; width: 230px;"}>
      <h1 id="mm-actions-header">Quick Actions</h1>
      <div
        id="mm-action-status-info"
        classList={{
          "visually-hidden": !isCurrentlyFilling(),
        }}
      >
        Filling...
      </div>
      <div id="mm-action-status-alert">
        <Show when={isFillError()}>
          <p class="mm-action-status-error">
            Error filling form. Please check console for details.
          </p>
        </Show>
        <For each={errorMessages()}>
          {(message) => <p class="mm-action-status-error">{message}</p>}
        </For>
      </div>
      <button class="mm-btn" onclick={submitSaveWork} style="background: #888f95">
        Save Work
      </button>
      <button class="mm-btn" onclick={submitCheckAndSaveWork} style="background: #888f95">
        Check Answers and Save
      </button>
      <hr style="width: 100%;" />
      <button class="mm-btn" onclick={scrollToFirstRequiredQuestion} style="background: #db4747d4;">
        Find * Required warnings
      </button>

      <Show when={surveyFeatures.length !== 0}>
        <hr style="width: 100%;" />
        <For each={surveyFeatures}>
          {(feature) => (
            <button class="mm-btn" onclick={() => handleFeatureClick(feature)}>
              {feature.featureName}
            </button>
          )}
        </For>
      </Show>
    </div>
  );
}
