import System from "@/models/system";
import paths from "@/utils/paths";
import showToast from "@/utils/toast";
import { ArrowSquareOut } from "@phosphor-icons/react";
import { useState } from "react";
import { Link } from "react-router-dom";
import Toggle from "@/components/lib/Toggle";

export default function LiveSyncToggle({ enabled = false, onToggle }) {
  const [status, setStatus] = useState(enabled);

  async function toggleFeatureFlag() {
    const updated =
      await System.experimentalFeatures.liveSync.toggleFeature(!status);
    if (!updated) {
      showToast("Failed to update status of feature.", "error", {
        clear: true,
      });
      return false;
    }

    setStatus(!status);
    showToast(
      `Live document content sync has been ${
        !status ? "enabled" : "disabled"
      }.`,
      "success",
      { clear: true }
    );
    onToggle();
  }

  return (
    <div className="p-4">
      <div className="flex flex-col gap-y-6 max-w-[500px]">
        <div className="flex items-center justify-between">
          <h2 className="text-theme-text-primary text-md font-bold">
            Automatic Document Content Sync
          </h2>
          <Toggle size="lg" enabled={status} onChange={toggleFeatureFlag} />
        </div>
        <div className="flex flex-col space-y-4">
          <p className="text-theme-text-secondary text-sm">
            Enable the ability to specify a document to be "watched". Watched
            document's content will be regularly fetched and updated in
            AnythingLLM.
          </p>
          <p className="text-theme-text-secondary text-sm">
            Watched documents will automatically update in all workspaces they
            are referenced in at the same time of update.
          </p>
          <p className="text-theme-text-secondary text-xs italic">
            This feature only applies to web-based content, such as websites,
            Confluence, YouTube, and GitHub files.
          </p>
        </div>
      </div>
      <div className="mt-8">
        <ul className="space-y-2">
          <li>
            <a
              href="https://docs.anythingllm.com/beta-preview/active-features/live-document-sync"
              target="_blank"
              className="text-sm text-blue-400 light:text-blue-500 hover:underline flex items-center gap-x-1"
              rel="noreferrer"
            >
              <ArrowSquareOut size={14} />
              <span>Feature Documentation and Warnings</span>
            </a>
          </li>
          <li>
            <Link
              to={paths.experimental.liveDocumentSync.manage()}
              className="text-sm text-blue-400 light:text-blue-500 hover:underline"
            >
              Manage Watched Documents &rarr;
            </Link>
          </li>
        </ul>
      </div>
    </div>
  );
}
