import { useToken } from "@/hooks/useToken";
import { api_endpoint, fetcher } from "../lib/utils";
import useSWR from "swr";
import { Skeleton } from "primereact/skeleton";

import { Dropdown } from "primereact/dropdown";
import { useEffect, useState } from "react";

import styles from "./ActionsDropdown.module.css";

function ActionsDropdown() {
  const { token } = useToken();
  const {
    data: actions,
    error,
    isLoading,
  } = useSWR(`${api_endpoint}/actions?token=${token}`, fetcher);

  let options: any[] | undefined = [];

  const [lazyItems, setLazyItems] = useState([]);
  const [lazyLoading, setLazyLoading] = useState(false);

  const onLazyLoad = async (event: any) => {
    setLazyLoading(true);

    const request = await fetch(`${api_endpoint}/actions?token=${token}`);

    const actions_data = await request.json();

    const options = actions_data.map((action: any) => {
      return {
        label: action.name,
        value: action.id,
        logo_url: action.logo_url,
      };
    });

    setLazyItems(options);
    setLazyLoading(false);
  };

  useEffect(() => {
    if (!actions) return;
    console.log(actions);
    options = actions.map((action: any) => {
      return {
        label: action.name,
        value: action.id,
        logo_url: action.logo_url,
      };
    });

    console.log("options", options);
  }, [actions]);

  const actionOptionTemplate = (option: any) => {
    return (
      <div>
        <img
          className={styles.action_img}
          alt={option.label}
          src={option.logo_url}
        />
        <div className={styles.action_img}>{option.label}</div>
      </div>
    );
  };

  return (
    <>
      {options && (
        <>
          <div className={styles.dropdown_actions}></div>
          <Dropdown
            options={lazyItems}
            //onChange={onLazyItemChange}
            virtualScrollerOptions={{
              lazy: true,
              onLazyLoad: onLazyLoad,
              itemSize: 38,
              showLoader: true,
              loading: lazyLoading,
              delay: 250,
              loadingTemplate: (options) => {
                return (
                  <div
                    className="flex align-items-center p-2"
                    style={{ height: "38px" }}
                  >
                    <Skeleton
                      width={options.even ? "60%" : "50%"}
                      height="1rem"
                    />
                  </div>
                );
              },
            }}
            itemTemplate={actionOptionTemplate}
            placeholder="Add action"
          />
        </>
      )}
    </>
  );
}

export { ActionsDropdown };
