import React, { useState, useEffect } from "react";
import "./frontend-style.scss";
import ContentCard from "@app/components/content-card/ContentCard";
import { Post } from "@app/models/api";
import InfiniteScroll from "@app/components/InfiniteScroll/InfiniteScroll";
import CustomizableHeader from "@app/components/customizable-header/CustomizableHeader";
import PageFooter from "@app/components/page-footer/PageFooter";
import { ButtonProps } from "@app/models/components";
import Skeleton from "@app/components/skeleton/Skeleton";
import { mapMediaToIcon } from "@app/services/utilities";
import { PinIcon, DarkSfSyncLogo, SfSyncLogo } from "@app/assets/images/icons";

const App = () => {
  const [isFetching, setIsFetching] = useState(true);
  const [mode, setMode] = useState(
    postsData.footer_mode ? postsData.footer_mode : "automatic"
  );

  const showFooter = postsData.show_footer ? postsData.show_footer : "on";
  const localization = postsData.localization;

  const displayHeader =
    postsData?.page_header?.title || postsData?.page_header?.image_url;

  useEffect(() => {
    if (postsData.footer_mode === "automatic" || !postsData.footer_mode) {
      const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
      const handleSystemPreference = () => {
        setMode(mediaQuery.matches ? "dark" : "light");
      };

      handleSystemPreference();

      mediaQuery.addEventListener("change", handleSystemPreference);

      return () =>
        mediaQuery.removeEventListener("change", handleSystemPreference);
    } else {
      setMode(postsData.footer_mode ?? "light");
    }
  }, [postsData.footer_mode]);

  useEffect(() => {
    setTimeout(() => {
      setIsFetching(false);
    }, 1500);
  }, []);

  const skeletonItems = Array.from({ length: 12 }, (_, index) => index + 1);

  const renderItem = (post: Post) => {
    return (
      (post?.media_url || post?.thumbnail_url) && (
        <div key={post.id} className="sfsyncFrontend-gridItem">
          <a href={post.link} target="_blank">
            <ContentCard
              imageSrc={post?.thumbnail_url || post?.media_url || ""}
              imageAlign={post.thumbnail_url ? "center center" : "left top"}
              tags={[
                {
                  icon: post?.pinned ? PinIcon : mapMediaToIcon(post),
                  style: {
                    backgroundColor: "transparent",
                    color: "white",
                  },
                },
              ]}
            />
          </a>
        </div>
      )
    );
  };

  const handleActionButtonClick = () => {
    const url = postsData?.page_header?.action_button?.action_url;
    window.open(url, "_blank");
  };

  const getActionBtnProps = (): ButtonProps | undefined => {
    const actionButton = postsData?.page_header?.action_button;

    if (!actionButton?.text || !actionButton?.action_url) return undefined;

    return {
      text: actionButton?.text,
      onClickHandler: handleActionButtonClick,
      style: {
        backgroundColor: actionButton?.bg_color || "#131339",
        color: actionButton?.text_color || "#fff",
      },
      type: "button",
    };
  };

  const getFooterActionBtnProps = (): ButtonProps | undefined => {
    return {
      text: localization.get_it_now,
      onClickHandler: () => {},
      style: {
        fontSize: "1rem",
        padding: "1.5rem 2rem",
        backgroundColor: "#fff",
        color: "#474747",
        border: "1px solid #474747",
      },
      type: "link",
      href: "https://wordpress.org/plugins/social-feed-sync/",
      target: "_blank",
    };
  };

  return (
    <div className="sfsyncFrontend">
      {displayHeader && (
        <header className="sfsyncFrontend-header">
          <CustomizableHeader
            title={postsData?.page_header?.title}
            avatar={{ src: postsData?.page_header?.image_url }}
            actionButton={getActionBtnProps()}
            headerLink={postsData?.page_header?.header_link}
            socialIcons={postsData?.page_header?.socialIcons}
          />
        </header>
      )}
      <div className="sfsyncFrontend-postsGrid">
        {isFetching &&
          skeletonItems.map((item) => (
            <div key={item} className="sfsyncFrontend-gridItem">
              <Skeleton width="100%" variant="rectangle" />
            </div>
          ))}

        {!isFetching && !!postsData?.posts?.length && (
          <InfiniteScroll
            items={postsData?.posts}
            itemsToShow={30}
            renderItem={renderItem}
          />
        )}
      </div>
      {showFooter === "on" && (
        <PageFooter
          title={localization.powered_by}
          subtitle={localization.the_ultimate_link_in_bio_tool_for_wordpress}
          icon={mode === "dark" ? DarkSfSyncLogo : SfSyncLogo}
          actionButton={getFooterActionBtnProps()}
          mode={mode}
        />
      )}
    </div>
  );
};

export default App;
