import { __ } from "@wordpress/i18n";
import { ArrowUpRight, Sparkle, Sparkles, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import Modal from "@libs/modal";
import {
  ASSISTANTS,
  buildAssistantPrompt,
  QUESTION_EXAMPLES,
  QUESTION_LIMIT,
} from "@libs/assistant-prompt";
import AssistantLogo from "./AssistantLogo";
import "../scss/main/components/_ask-anything-dialog.scss";

const EXAMPLE_TYPE_MS = 1200;
const EXAMPLE_HOLD_MS = 4300;

/** Sends a support question to a visitor's own ChatGPT or Claude session. */
const AskAnythingDialog = ({ isOpen, onClose, docsUrl, pageUrl }) => {
  const [question, setQuestion] = useState("");
  const [error, setError] = useState("");
  const [placeholder, setPlaceholder] = useState(QUESTION_EXAMPLES[0]);
  const questionRef = useRef(null);
  const promptRef = useRef(null);
  const shownExamplesRef = useRef(new Set());
  const currentExampleRef = useRef(QUESTION_EXAMPLES[0]);

  useEffect(() => {
    if (!isOpen) {
      return undefined;
    }

    setError("");
    const focusTimer = window.setTimeout(() => questionRef.current?.focus(), 80);

    return () => window.clearTimeout(focusTimer);
  }, [isOpen]);

  useEffect(() => {
    const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
    let exampleFrame;
    let exampleTimer;
    let rotatingExamples = false;

    const canRotateExamples = () =>
      isOpen && !question && !reducedMotion.matches && !document.hidden;

    const renderExample = (text) => {
      setPlaceholder((current) => (current === text ? current : text));
    };

    const stopExamples = () => {
      window.cancelAnimationFrame(exampleFrame);
      window.clearTimeout(exampleTimer);
      renderExample(currentExampleRef.current);
    };

    const typeNextExample = () => {
      if (!canRotateExamples()) {
        syncExampleAnimation();
        return;
      }

      if (shownExamplesRef.current.size === QUESTION_EXAMPLES.length) {
        shownExamplesRef.current.clear();
      }

      const choices = QUESTION_EXAMPLES.filter(
        (example) =>
          !shownExamplesRef.current.has(example) &&
          example !== currentExampleRef.current,
      );
      const nextExample = choices[Math.floor(Math.random() * choices.length)];
      currentExampleRef.current = nextExample;
      shownExamplesRef.current.add(nextExample);

      const start = performance.now();
      const typeFrame = (now) => {
        if (!canRotateExamples()) {
          syncExampleAnimation();
          return;
        }

        const progress = Math.min(1, (now - start) / EXAMPLE_TYPE_MS);
        const length = Math.max(1, Math.ceil(nextExample.length * progress));
        renderExample(nextExample.slice(0, length));

        if (progress === 1) {
          exampleTimer = window.setTimeout(typeNextExample, EXAMPLE_HOLD_MS);
        } else {
          exampleFrame = window.requestAnimationFrame(typeFrame);
        }
      };

      typeFrame(start);
    };

    const syncExampleAnimation = () => {
      const shouldRotate = canRotateExamples();
      if (rotatingExamples === shouldRotate) {
        return;
      }

      rotatingExamples = shouldRotate;
      if (shouldRotate) {
        typeNextExample();
      } else {
        stopExamples();
      }
    };

    syncExampleAnimation();
    reducedMotion.addEventListener("change", syncExampleAnimation);
    document.addEventListener("visibilitychange", syncExampleAnimation);

    return () => {
      reducedMotion.removeEventListener("change", syncExampleAnimation);
      document.removeEventListener("visibilitychange", syncExampleAnimation);
      rotatingExamples = false;
      stopExamples();
    };
  }, [isOpen, question]);

  const handleQuestionChange = (event) => {
    setQuestion(event.target.value);
    if (error) {
      setError("");
    }
  };

  const handleSubmit = (event) => {
    const text = question.trim();

    if (text.length < 2 || text.length > QUESTION_LIMIT) {
      event.preventDefault();
      setError(
        text.length > QUESTION_LIMIT
          ? __("Keep your question under 2,000 characters.", "arraysubs")
          : __("Write your question first.", "arraysubs"),
      );
      questionRef.current?.focus();
      return;
    }

    if (promptRef.current) {
      promptRef.current.value = buildAssistantPrompt(text, { docsUrl, pageUrl });
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      size="md"
      className="arraysubs-assistant-dialog"
      showCloseButton={false}
      ariaLabel={__("Ask ChatGPT or Claude", "arraysubs")}
    >
      <div className="arraysubs-assistant-dialog__panel">
        <div className="arraysubs-assistant-dialog__art" aria-hidden="true">
          <span className="arraysubs-assistant-dialog__arc" />
          <span className="arraysubs-assistant-dialog__dots" />
          <span className="arraysubs-assistant-dialog__burst"><Sparkle /></span>
          <span className="arraysubs-assistant-dialog__dash" />
        </div>

        <div className="arraysubs-assistant-dialog__top">
          <span className="arraysubs-assistant-dialog__eyebrow">
            <Sparkles aria-hidden="true" />
            {__("Fast, Accurate, Free", "arraysubs")}
          </span>
          <button
            type="button"
            className="arraysubs-assistant-dialog__close"
            onClick={onClose}
            aria-label={__("Close assistant dialog", "arraysubs")}
          >
            <X aria-hidden="true" />
          </button>
        </div>

        <h2>{__("Need an urgent answer?", "arraysubs")}</h2>
        <p className="arraysubs-assistant-dialog__description">
          {__("Want to know if ", "arraysubs")}
          <strong>{__("ArraySubs meets your requirements, or need a step-by-step guide", "arraysubs")}</strong>
          {__(" to get set up quickly? Ask ", "arraysubs")}
          <strong>{__("ChatGPT or Claude", "arraysubs")}</strong>
          {__(" now. We'll include the official user guide to help them give accurate answers.", "arraysubs")}
        </p>

        <form
          className="arraysubs-assistant-dialog__form"
          method="get"
          action={ASSISTANTS[0].url}
          target="_blank"
          rel="noopener noreferrer"
          noValidate
          onSubmit={handleSubmit}
        >
          <label htmlFor="arraysubs-assistant-question">
            {__("What would you like to know?", "arraysubs")}
          </label>
          <textarea
            id="arraysubs-assistant-question"
            ref={questionRef}
            rows="6"
            value={question}
            placeholder={placeholder}
            required
            minLength="2"
            maxLength={QUESTION_LIMIT}
            onChange={handleQuestionChange}
            aria-describedby="arraysubs-assistant-question-error"
            aria-invalid={error ? "true" : undefined}
          />
          <p
            id="arraysubs-assistant-question-error"
            className="arraysubs-assistant-dialog__error"
            role="status"
            hidden={!error}
          >
            {error}
          </p>
          <input ref={promptRef} type="hidden" name="q" />

          <div className="arraysubs-assistant-dialog__actions">
            {ASSISTANTS.map((assistant) => (
              <button
                key={assistant.id}
                type="submit"
                className={`arraysubs-assistant-action arraysubs-assistant-action--${assistant.id}`}
                formAction={assistant.url}
              >
                <AssistantLogo provider={assistant.id} />
                <span>{`${__("Ask", "arraysubs")} ${assistant.name}`}</span>
                <ArrowUpRight aria-hidden="true" />
                <span className="screen-reader-text">{__("(opens in a new tab)", "arraysubs")}</span>
              </button>
            ))}
          </div>
        </form>
      </div>
    </Modal>
  );
};

export default AskAnythingDialog;
