import { useState } from "react";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { alphaSort } from "../../utils/sorters";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { useTranslation } from "react-i18next";
import AuditTrailValuesComponent from "../audit-trail-values/audit-trail-values.component";
import { pageLimit } from "../../utils/config";

export default function AuditTrailListComponent({ loading, data }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: {}
  });
  const { t } = useTranslation();
  const columns = [
    {
      title: t("audit.fields.created"),
      dataIndex: " created",
      key: " created",
      width: "10%",
      render: (text, record) => <DateTimeFormatter>{record.created}</DateTimeFormatter>,
      sorter: (a, b) => a.created - b.created,
      sortOrder: state.sortedInfo.columnKey === "created" && state.sortedInfo.order
    },
    {
      title: t("audit.fields.operation"),
      dataIndex: "operation",
      key: "operation",
      width: "10%",
      sorter: (a, b) => alphaSort(a.operation, b.operation),
      sortOrder: state.sortedInfo.columnKey === "operation" && state.sortedInfo.order
    },
    {
      title: t("audit.fields.values"),
      dataIndex: " old_val",
      key: " old_val",
      width: "10%",
      render: (text, record) => <AuditTrailValuesComponent oldV={record.old_val} newV={record.new_val} />
    },
    {
      title: t("audit.fields.useremail"),
      dataIndex: "useremail",
      key: "useremail",
      width: "10%",
      sorter: (a, b) => alphaSort(a.useremail, b.useremail),
      sortOrder: state.sortedInfo.columnKey === "useremail" && state.sortedInfo.order
    }
  ];

  const formItemLayout = {
    labelCol: {
      xs: { span: 12 },
      sm: { span: 5 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 }
    }
  };
  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };

  return (
    <ResponsiveTable
      {...formItemLayout}
      loading={loading}
      pagination={{ placement: "top", defaultPageSize: pageLimit }}
      columns={columns}
      mobileColumnKeys={[" created", "operation", " old_val", "useremail"]}
      rowKey="id"
      dataSource={data}
      onChange={handleTableChange}
    />
  );
}
