import React, { useState, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import Column from "../../../../components/common/columns";
import Table from "../../../../components/common/Table";
import { Glossary } from "../services/glossaryService";
import authentication from "../../../frame/services/authenticationService";

interface GlossariesTableProps {
  data?: Glossary;
  onDelete?: (keyValue: any) => void;
}

interface CustomColumn extends Column<customField> {
  isCustom: boolean;
}

interface customField {
  [key: string]: any;
}

const GlossariesTable: React.FC<GlossariesTableProps> = ({
  data,
  onDelete,
}) => {
  const { t } = useTranslation();

  const [columnsList, setColumnsList] = useState<CustomColumn[]>([]);

  const baseColumns: CustomColumn[] = useMemo(
    () => [
      {
        key: "name",
        label: t("Name"),
        order: "asc",
        link: "/glossaries/{0}",
        isCustom: false,
      },
    ],
    [t],
  );

  const findValueById = (glossaryData: Glossary, key: string) => {
    if (glossaryData.customFieldValues) {
      for (const value of glossaryData.customFieldValues) {
        if (String(value.id.id) === key) {
          const displayValue: string = value.values[0].displayValue ?? "";
          return displayValue;
        }
      }
    }
    return undefined;
  };

  const paginatedData = useMemo(() => {
    if (!data) {
      return {
        count: 0,
        page: 1,
        pageSize: 1,
        totalPages: 0,
        data: [],
      };
    }

    const pagedData = data.children.map((x) => {
      const dataItem: customField = {
        id: x.id,
        name: x.name,
      };

      for (const column of columnsList) {
        if (column.isCustom) {
          dataItem[column.key] = findValueById(x, column.key);
        }
      }

      return dataItem;
    });

    return {
      count: 1,
      page: 1,
      pageSize: 1,
      totalPages: 1,
      data: pagedData,
    };
  }, [data, columnsList]);

  useEffect(() => {
    const newColumnsList = [...baseColumns];

    if (data?.childCustomFieldDefinition) {
      for (const customfield of data.childCustomFieldDefinition) {
        newColumnsList.push({
          key: String(customfield.id),
          label: customfield.name,
          order: "asc",
          isCustom: true,
        });
      }
    }

    setColumnsList(newColumnsList);
  }, [baseColumns, data]);

  const handleAuditParams = (item: any) => {
    return {
      entityName: "e_suite.Database.Core.Tables.Glossaries.Glossary",
      primaryKey: `{"Id":${item.id}}`,
    };
  };

  const editPath = authentication.hasAccess("EditGlossary")
    ? "/glossaries/edit/{0}"
    : undefined;
  const doDelete = authentication.hasAccess("DeleteGlossary")
    ? onDelete
    : undefined;
  const showAudit = authentication.hasAccess("ViewAuditLog")
    ? handleAuditParams
    : undefined;

  return (
    <Table
      data={paginatedData}
      keyName="id"
      columns={columnsList}
      editPath={editPath}
      onDelete={doDelete}
      onAuditParams={showAudit}
    />
  );
};

export default GlossariesTable;
