import { useCallback, useEffect, useState } from "react";
import Column from "../../components/common/columns";
import { Paginated } from "../../services/Paginated";
import ErrorLogsTable from "./components/errorLogsTable";
import errorLogsService, { ErrorLog } from "./services/errorLogsService";
import { useTranslation } from "react-i18next";
import { Namespaces } from "../../i18n/i18n";

const ErrorLogs = (): JSX.Element => {
  const { t } = useTranslation<typeof Namespaces.Common>();
  const [pagedData, setPagedData] = useState<Paginated<ErrorLog>>({
    page: 1,
    pageSize: 10,
    count: 0,
    totalPages: 1,
    data: [],
  });
  const [sortColumn, setSortColumn] = useState<Column<ErrorLog>>({
    key: "Id",
    label: t("Id"),
    order: "desc",
  });
  const [filters, setFilters] = useState<Map<string, string>>(
    new Map<string, string>(),
  );

  const loadErrorLogs = useCallback(
    async (
      page: number,
      pageSize: number,
      column: Column<ErrorLog>,
      filterMap: Map<string, string>,
    ) => {
      const data = await errorLogsService.getErrorLogs(
        page,
        pageSize,
        column.key,
        column.order === "asc",
        filterMap,
      );
      if (data) {
        setPagedData(data);
      }
    },
    [],
  );

  useEffect(() => {
    loadErrorLogs(pagedData.page, pagedData.pageSize, sortColumn, filters);
  }, [loadErrorLogs]);

  const changePage = useCallback(
    async (page: number, pageSize: number) => {
      await loadErrorLogs(page, pageSize, sortColumn, filters);
    },
    [loadErrorLogs, sortColumn, filters],
  );

  const onSort = useCallback(
    async (nextSortColumn: Column<ErrorLog>) => {
      setSortColumn(nextSortColumn);
      await loadErrorLogs(
        pagedData.page,
        pagedData.pageSize,
        nextSortColumn,
        filters,
      );
    },
    [loadErrorLogs, pagedData.page, pagedData.pageSize, filters],
  );

  const onSearch = useCallback(
    async (name: string, value: string) => {
      const nextFilters = new Map(filters);
      nextFilters.set(name, value);
      setFilters(nextFilters);

      await loadErrorLogs(
        pagedData.page,
        pagedData.pageSize,
        sortColumn,
        nextFilters,
      );
    },
    [loadErrorLogs, pagedData.page, pagedData.pageSize, sortColumn, filters],
  );

  return (
    <div>
      <ErrorLogsTable
        data={pagedData}
        sortColumn={sortColumn}
        onChangePage={changePage}
        onSort={onSort}
        onSearch={onSearch}
      />
    </div>
  );
};

export default ErrorLogs;
