// React Grid Logic
import { useEffect, useMemo, useState } from "react";

// Theme
import type { ColDef, ValueFormatterParams } from "ag-grid-community";
import { AllCommunityModule, ModuleRegistry } from "ag-grid-community";

ModuleRegistry.registerModules([AllCommunityModule]);

// Core CSS
import { AgGridReact } from "ag-grid-react";
import { useInvoices } from "../hooks/use-invoices";

/**
 * Fetch example Json data
 * Not recommended for production use!
 */
export const useFetchJson = <T,>(url: string, limit?: number) => {
  const [data, setData] = useState<T[]>();
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);

      // Note error handling is omitted here for brevity
      const response = await fetch(url);
      const json = await response.json();
      const data = limit ? json.slice(0, limit) : json;
      setData(data);
      setLoading(false);
    };
    fetchData();
  }, [url, limit]);
  return { data, loading };
};

// Row Data Interface
interface IRow {
  mission: string;
  company: string;
  location: string;
  date: string;
  time: string;
  rocket: string;
  price: number;
  successful: boolean;
}

// Create new GridExample component
export const InvoicesGrid = () => {
  const { useList } = useInvoices();

  const { data, isLoading, isPending, isError, error } = useList({});

  // Column Definitions: Defines & controls grid columns.
  const [colDefs] = useState<ColDef[]>([
    { field: "invoice_number" },
    { field: "invoice_series" },
    {
      field: "status",
    },

    { field: "issue_date" },
    { field: "operation_date" },
    {
      field: "subtotal",
      valueFormatter: (params: ValueFormatterParams) => {
        return "0 €";
        //return `£${params.value.toLocaleString()}`;
      },
    },
    {
      field: "total",
      valueFormatter: (params: ValueFormatterParams) => {
        return "0 €";
        //return `£${params.value.toLocaleString()}`;
      },
    },
  ]);

  // Apply settings across all columns
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      filter: true,
      sortable: false,
      resizable: false,
    };
  }, []);

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