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

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 { useCustomersQuery } from "../hooks";
import { useTranslation } from "../i18n";
import { CustomerStatusBadge } from "./customer-status-badge";

ModuleRegistry.registerModules([AllCommunityModule]);

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

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

  // Column Definitions: Defines & controls grid columns.
  const [colDefs] = useState<ColDef[]>([
    { field: "name", headerName: t("pages.list.grid_columns.name"), minWidth: 300 },
    {
      field: "tin",
      headerName: t("pages.list.grid_columns.tin"),
      maxWidth: 120,
    },
    {
      field: "city",
      headerName: t("pages.list.grid_columns.city"),
    },
    {
      field: "email_primary",
      headerName: t("pages.list.grid_columns.email"),
    },
    {
      field: "phone_primary",
      headerName: t("pages.list.grid_columns.phone"),
      maxWidth: 120,
    },

    {
      field: "mobile_primary",
      headerName: t("pages.list.grid_columns.mobile"),
      maxWidth: 120,
    },
    {
      field: "status",
      headerName: t("pages.list.grid_columns.status"),
      maxWidth: 125,
      cellRenderer: (params: ValueFormatterParams) => {
        return <CustomerStatusBadge status={params.value} />;
      },
    },
    {
      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(`/customers/${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]
  );

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