import React, { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
import Column from "../../../components/common/columns";
import { Paginated } from "../../../services/Paginated";
import SsoManagerTable from "./components/ssoManagerTable";
import ssoManagerService, {
  GetSsoProvider,
} from "./services/ssoManagerService";
import Button, { ButtonType } from "../../../components/common/Button";
import Loading from "../../../components/common/Loading";
import Permission from "../../../components/common/Permission";

const SsoManager: React.FC = () => {
  const { t } = useTranslation(Namespaces.Common);
  const [loaded, setLoaded] = useState(false);
  const [pagedData, setPagedData] = useState<Paginated<GetSsoProvider>>({
    page: 1,
    pageSize: 10,
    count: 0,
    totalPages: 1,
    data: [],
  });
  const [sortColumn, setSortColumn] = useState<Column<GetSsoProvider>>({
    key: "name",
    label: t("Name"),
    order: "asc",
  });
  const [filters, setFilters] = useState<Map<string, string>>(
    new Map<string, string>(),
  );

  const changePage = useCallback(
    async (page: number, pageSize: number) => {
      const data = await ssoManagerService.getSsoProviders(
        page,
        pageSize,
        sortColumn.key,
        sortColumn.order === "asc",
        filters,
      );
      if (data) {
        setLoaded(true);
        setPagedData(data);
      } else {
        setLoaded(false);
      }
    },
    [filters, sortColumn.key, sortColumn.order],
  );

  const onSort = async (newSortColumn: Column<GetSsoProvider>) => {
    const { page, pageSize } = pagedData;
    const data = await ssoManagerService.getSsoProviders(
      page,
      pageSize,
      newSortColumn.key,
      newSortColumn.order === "asc",
      filters,
    );
    if (data) {
      setLoaded(true);
      setPagedData(data);
      setSortColumn(newSortColumn);
    } else {
      setLoaded(false);
    }
  };

  const onSearch = async (name: string, value: string) => {
    const { page, pageSize } = pagedData;
    const newFilters = new Map(filters);
    newFilters.set(name, value);

    const data = await ssoManagerService.getSsoProviders(
      page,
      pageSize,
      sortColumn.key,
      sortColumn.order === "asc",
      newFilters,
    );
    if (data) {
      setLoaded(true);
      setFilters(newFilters);
      setPagedData(data);
    } else {
      setLoaded(false);
    }
  };

  const onDelete = async (keyValue?: GetSsoProvider) => {
    const response = await ssoManagerService.deleteSsoProvider(
      keyValue?.id,
      keyValue?.guid,
    );
    if (response) {
      await changePage(pagedData.page, pagedData.pageSize);
    }
  };

  useEffect(() => {
    const loadInitial = async () => {
      const data = await ssoManagerService.getSsoProviders(
        1,
        10,
        "name",
        true,
        filters,
      );
      if (data) {
        setLoaded(true);
        setPagedData(data);
      } else {
        setLoaded(false);
      }
    };

    void loadInitial();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <Loading loaded={loaded}>
      <Permission privilegeKey="AddSsoProvider">
        <div>
          <Button buttonType={ButtonType.primary} to="add">
            {t("Add")}
          </Button>
        </div>
      </Permission>
      <hr />
      <SsoManagerTable
        data={pagedData}
        sortColumn={sortColumn}
        onChangePage={changePage}
        onSort={onSort}
        onSearch={onSearch}
        onDelete={onDelete}
      />
    </Loading>
  );
};

export default SsoManager;
