import { AG_GRID_LOCALE_ES } from "@ag-grid-community/locale";
import type {
  SizeColumnsToContentStrategy,
  SizeColumnsToFitGridStrategy,
  SizeColumnsToFitProvidedWidthStrategy,
  ValueFormatterParams,
} from "ag-grid-community";
import { AllCommunityModule, ColDef, GridOptions, ModuleRegistry } from "ag-grid-community";
import { useMemo, useState } from "react";

import { MoneyDTO } from "@erp/core";
import { formatDate, formatMoney } from "@erp/core/client";
import { ErrorOverlay } from "@repo/rdx-ui/components";
import { Button } from "@repo/shadcn-ui/components";
import { AgGridReact } from "ag-grid-react";
import { ChevronRightIcon } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useCustomerInvoicesQuery } from "../hooks";
import { useTranslation } from "../i18n";
import { CustomerInvoiceStatusBadge } from "./customer-invoice-status-badge";

ModuleRegistry.registerModules([AllCommunityModule]);

// Create new GridExample component
export const CustomerInvoicesListGrid = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const {
    data: customersData,
    isLoading: isLoadingCustomerInvoices,
    isError: isLoadError,
    error: loadError,
  } = useCustomerInvoicesQuery({
    pagination: {
      pageSize: 999,
    },
  });

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

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

    {
      field: "invoice_date",
      headerName: t("pages.list.grid_columns.invoice_date"),
      valueFormatter: (params: ValueFormatterParams) => {
        return formatDate(params.value);
      },
    },
    { field: "recipient.tin" },
    { field: "recipient.name" },

    { field: "recipient.city" },
    { field: "recipient.province" },
    { field: "recipient.postal_code" },
    {
      field: "taxable_amount",
      headerName: t("pages.list.grid_columns.taxable_amount"),
      valueFormatter: (params: ValueFormatterParams) => {
        const rawValue: MoneyDTO = params.value;
        return formatMoney(rawValue);
      },
    },
    {
      field: "taxes_amount",
      headerName: t("pages.list.grid_columns.taxable_amount"),
      valueFormatter: (params: ValueFormatterParams) => {
        const rawValue: MoneyDTO = params.value;
        return formatMoney(rawValue);
      },
    },

    {
      field: "total_amount",
      headerName: t("pages.list.grid_columns.total_amount"),
      valueFormatter: (params: ValueFormatterParams) => {
        const rawValue: MoneyDTO = params.value;
        return formatMoney(rawValue);
      },
    },
    {
      colId: "actions",
      headerName: t("pages.list.grid_columns.actions", "Actions"),
      cellRenderer: (params: ValueFormatterParams) => {
        const { data } = params;
        return (
          <Button
            variant='secondary'
            size='icon'
            className='size-8'
            onClick={() => {
              navigate(`/customer-invoices/${data.id}/edit`);
            }}
          >
            <ChevronRightIcon />
          </Button>
        );
      },
    },
  ]);

  const autoSizeStrategy = useMemo<
    | SizeColumnsToFitGridStrategy
    | SizeColumnsToFitProvidedWidthStrategy
    | SizeColumnsToContentStrategy
  >(() => {
    return {
      type: "fitGridWidth",
      defaultMinWidth: 100,
      columnLimits: [{ colId: "actions", minWidth: 75, maxWidth: 75 }],
    };
  }, []);

  const gridOptions: GridOptions = useMemo(
    () => ({
      columnDefs: colDefs,
      autoSizeStrategy: autoSizeStrategy,
      defaultColDef: {
        editable: false,
        flex: 1,
        filter: false,
        sortable: false,
        resizable: true,
      },
      pagination: true,
      paginationPageSize: 15,
      paginationPageSizeSelector: [10, 15, 20, 30, 50],
      localeText: AG_GRID_LOCALE_ES,
    }),
    [autoSizeStrategy, colDefs]
  );

  if (isLoadError) {
    return (
      <>
        <ErrorOverlay
          errorMessage={
            (loadError as Error)?.message ??
            t("pages.update.loadErrorMsg", "Inténtalo de nuevo más tarde.")
          }
        />
      </>
    );
  }

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