import { WebView } from "react-native-webview";
import { useRef } from "react";

export default function HomeScreen() {
  const webviewRef = useRef(null);

  const injectedJavaScript = `
    (function() {
      try {
        // Inject CSS for toast notifications
        const style = document.createElement('style');
        style.innerHTML = \`
          #toast-container {
            position: fixed;
            top: 50px;
            right: 20px;
            left: 20px;
            z-index: 999999;
            display: flex;
            flex-direction: column;
            gap: 10px;
            pointer-events: auto;
          }
          .toast {
            background-color: #1db146;
            color: #fff;
            font-weight: 800;
            padding: 12px 16px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            font-size: 16px;
            opacity: 1;
            position: relative;
            width: 90%;
            z-index: 99999999999;
            transition: opacity 0.5s ease;
          }
          .toast.fade-out {
            opacity: 0;
          }
        \`;
        document.head.appendChild(style);

        // Fact-checking logic
        let lastClickTime = 0;
        const COOLDOWN_DURATION = 60000;
        let buttonClicked = false;
        let fullCaption = "";
        let imageUrls = [];
        let isApiCallInProgress = false;

        // Toast notification function
        function showToast(message, duration = 5000) {
          const container = document.getElementById('toast-container') ||
            (() => {
              const cont = document.createElement('div');
              cont.id = 'toast-container';
              document.body.appendChild(cont);
              return cont;
            })();

          const toast = document.createElement('div');
          toast.className = 'toast';
          toast.textContent = message;
          container.appendChild(toast);

          setTimeout(() => {
            toast.classList.add('fade-out');
            toast.addEventListener('transitionend', () => {
              toast.remove();
            });
          }, duration);
        }

        // Function to disable all buttons
        function disableAllButtons() {
          document.querySelectorAll("button").forEach((btn) => {
            btn.disabled = true;
            btn.style.opacity = "0.5";
            btn.style.cursor = "not-allowed";
          });
        }

        // Function to enable all buttons
        function enableAllButtons() {
          document.querySelectorAll("button").forEach((btn) => {
            btn.disabled = false;
            btn.style.opacity = "1";
            btn.style.cursor = "pointer";
          });
        }

        // Fact-checking API call
        async function checkFacts(caption, button) {
          try {
            isApiCallInProgress = true;
            disableAllButtons();
            const response = await fetch('http://localhost:8000/check-facts', {
              method: 'POST',
              headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ query: caption }),
            });

            if (!response.ok) {
              throw new Error('Network response was not ok');
            }

            const result = await response.json();
            showToast(result.evidence);
            button.textContent = 'Processed';
          } catch (error) {
            console.error('Error:', error);
            showToast('An error occurred while checking facts');
          } finally {
            isApiCallInProgress = false;
            enableAllButtons();
            button.disabled = false;
            button.style.opacity = "1";
          }
        }

        function collectPostData(post) {
          if (post.dataset.processed === "true") return;

          const captionElement = post.querySelector(
            "div.m div.m div[data-type='text'] div.native-text"
          );
          let caption = captionElement ? captionElement.textContent.trim() : null;

          const imageElements = post.querySelectorAll("div.m.bg-s13 img");
          let imageURLs = [];
          imageElements.forEach((imageElement) => {
            if (imageElement.src) imageURLs.push(imageElement.src);
          });

          if (buttonClicked) {
            fullCaption = caption;
            imageUrls.push(...imageURLs);
          }
          post.dataset.processed = "true";

          const button = createButton(post, caption, imageURLs);
          if (caption?.length > 30 || imageURLs.length > 0) {
            post.style.position = "relative";
            post.appendChild(button);
          }
        }

        function createButton(post, initialCaption, initialImageURLs) {
          const button = document.createElement("button");
          button.textContent = "Check";

          Object.assign(button.style, {
            position: "absolute",
            fontSize: "20px",
            right: "10px",
            bottom: "10px",
            background: "linear-gradient(135deg, #6a11cb, #2575fc)",
            color: "#fff",
            border: "none",
            padding: "12px 20px",
            borderRadius: "8px",
            cursor: "pointer",
            zIndex: 1000000,
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            gap: "8px",
            pointerEvents: "auto",
            transition: "all 0.3s",
          });

          button.addEventListener("click", (event) => {
            event.stopPropagation();
            const currentTime = new Date().getTime();

            lastClickTime = currentTime;

            button.disabled = true;
            button.textContent = "Processing...";
            button.style.opacity = "0.5";

            const seeMoreElement = post.querySelector("span[style*='color:#65676b']");

            if (seeMoreElement) {
              handleSeeMoreClick(
                seeMoreElement,
                post,
                button,
                initialCaption,
                initialImageURLs
              );
            } else {
              collectDataImmediately(post, button, initialCaption, initialImageURLs);
            }
          });

          return button;
        }

        async function handleSeeMoreClick(seeMoreElement, post, button, initialCaption, initialImageURLs) {
          return new Promise((resolve) => {
            setTimeout(() => {
              seeMoreElement.click();

              buttonClicked = true;

              setTimeout(async () => {
                await checkFacts(fullCaption, button);

                button.textContent = "Processed";
                button.style.opacity = "0.7";
                button.disabled = true;

                resolve();
              }, 2000);
            }, 100);
          });
        }

        async function collectDataImmediately(
          post,
          button,
          initialCaption,
          initialImageURLs
        ) {
          buttonClicked = true;

          const captionElement = post.querySelector(
            "div.m div.m div[data-type='text'] div.native-text"
          );
          let caption = captionElement
            ? captionElement.textContent.trim()
            : initialCaption;

          const imageElements = post.querySelectorAll("div.m img");
          let imageURLs = [];
          imageElements.forEach((imageElement) => {
            if (imageElement.src) imageURLs.push(imageElement.src);
          });

          if (imageURLs.length === 0) {
            imageURLs = initialImageURLs;
          }

          await checkFacts(caption, button);
          button.textContent = "Processed";
          button.style.opacity = "0.7";
          button.disabled = true;
        }

        // Mutation observer to handle new posts
        function handleMutations(mutationsList) {
          mutationsList.forEach((mutation) => {
            if (mutation.type === "childList" || mutation.type === "subtree") {
              document.querySelectorAll("div.m.bg-s3").forEach((post) => {
                if (!post.querySelector("button")) {
                  collectPostData(post);
                }
              });
            }
          });
        }

        const observer = new MutationObserver(handleMutations);
        observer.observe(document.querySelector(".m"), {
          childList: true,
          subtree: true,
        });

        document.addEventListener("DOMContentLoaded", () => {
          document.querySelectorAll("div.m.bg-s3").forEach((post) => {
            if (!post.dataset.processed) {
              collectPostData(post);
            }
          });
        });

        true; // Successful injection
      } catch (error) {
        console.error('Injection error:', error);
        false;
      }
    })();
  `;

  return (
    <WebView
      ref={webviewRef}
      source={{ uri: "https://m.facebook.com" }}
      injectedJavaScript={injectedJavaScript}
      startInLoadingState={true}
    />
  );
}