import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../../i18n/i18n";
import Button, { ButtonType } from "../../../components/common/Button";
import Column from "../../../components/common/columns";
import Permission from "../../../components/common/Permission";
import { Paginated } from "../../../services/Paginated";
import Loading from "../../../components/common/Loading";
import workflowTemplatesService, {
  ReadWorkflowTemplate,
} from "./services/WorkflowTemplateService";
import WorkflowTemplateManagerTable from "./components/WorkflowTemplateTable";

const WotkflowTemplateManager: React.FC = () => {
  const { t } = useTranslation(Namespaces.Common);
  const [loaded, setLoaded] = useState(false);
  const [pagedData, setPagedData] = useState<Paginated<ReadWorkflowTemplate>>({
    page: 1,
    pageSize: 10,
    count: 0,
    totalPages: 1,
    data: [],
  });
  const [sortColumn, setSortColumn] = useState<Column<ReadWorkflowTemplate>>({
    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 workflowTemplatesService.getTemplates(
        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<ReadWorkflowTemplate>) => {
    const { page, pageSize } = pagedData;
    const data = await workflowTemplatesService.getTemplates(
      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 workflowTemplatesService.getTemplates(
      page,
      pageSize,
      sortColumn.key,
      sortColumn.order === "asc",
      newFilters,
    );
    if (data) {
      setLoaded(true);
      setFilters(newFilters);
      setPagedData(data);
    } else {
      setLoaded(false);
    }
  };

  const onDelete = async (item?: ReadWorkflowTemplate) => {
    const response = await workflowTemplatesService.deleteTemplateVersion(
      item?.id,
      item?.guid,
    );
    if (response) {
      await changePage(pagedData.page, pagedData.pageSize);
    }
  };

  useEffect(() => {
    const loadInitial = async () => {
      const data = await workflowTemplatesService.getTemplates(
        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="AddOrganisation">
        <Button buttonType={ButtonType.primary} to="add">
          {t("Add")}
        </Button>
      </Permission>
      <hr />
      <WorkflowTemplateManagerTable
        data={pagedData}
        sortColumn={sortColumn}
        onChangePage={changePage}
        onSort={onSort}
        onSearch={onSearch}
        onDelete={onDelete}
      />
    </Loading>
  );
};

export default WotkflowTemplateManager;
