import { useState } from "react";

import { AG_GRID_LOCALE_ES } from "@ag-grid-community/locale";
// Grid
import type { ColDef, GridOptions, ValueFormatterParams } from "ag-grid-community";
import { AllCommunityModule, ModuleRegistry } from "ag-grid-community";

ModuleRegistry.registerModules([AllCommunityModule]);

import { MoneyDTO } from "@erp/core";
import { formatDate, formatMoney } from "@erp/core/client";
// Core CSS
import { AgGridReact } from "ag-grid-react";
import { useCustomerInvoicesQuery } from "../hooks";
import { useTranslation } from "../i18n";
import { CustomerInvoiceStatusBadge } from "./customer-invoice-status-badge";

// Create new GridExample component
export const CustomerInvoicesListGrid = () => {
  const { t } = useTranslation();
  const { data, isLoading, isPending, isError, error } = useCustomerInvoicesQuery({});

  // Column Definitions: Defines & controls grid columns.
  const [colDefs] = useState<ColDef[]>([
    {
      field: "invoice_status",
      filter: true,
      headerName: t("pages.list.grid_columns.invoice_status"),
      cellRenderer: (params: ValueFormatterParams) => {
        return <CustomerInvoiceStatusBadge status={params.value} />;
      },
    },

    { field: "invoice_number", headerName: t("pages.list.grid_columns.invoice_number") },
    { field: "invoice_series", headerName: t("pages.list.grid_columns.invoice_series") },

    {
      field: "invoice_date",
      headerName: t("pages.list.grid_columns.invoice_date"),
      valueFormatter: (params: ValueFormatterParams) => {
        return formatDate(params.value);
      },
    },
    {
      field: "total_price",
      headerName: t("pages.list.grid_columns.total_price"),
      valueFormatter: (params: ValueFormatterParams) => {
        const rawValue: MoneyDTO = params.value;
        return formatMoney(rawValue);
      },
    },
  ]);

  const gridOptions: GridOptions = {
    columnDefs: colDefs,
    defaultColDef: {
      editable: true,
      flex: 1,
      minWidth: 100,
      filter: false,
      sortable: false,
      resizable: true,
    },
    pagination: true,
    paginationPageSize: 10,
    paginationPageSizeSelector: [10, 20, 30, 50],
    localeText: AG_GRID_LOCALE_ES,
    rowSelection: { mode: "multiRow" },
  };

  // Container: Defines the grid's theme & dimensions.
  return (
    <div
      className='ag-theme-alpine'
      style={{
        height: "100%",
        width: "100%",
      }}
    >
      <AgGridReact rowData={data?.items ?? []} loading={isLoading || isPending} {...gridOptions} />
    </div>
  );
};
