import { Fragment, useMemo } from 'react';
import { getFaults } from '../../services/faults/get-faults';
import { Fault, FaultsResponse } from '../../models/fault.interface';
import { MRT_ColumnDef, MaterialReactTable } from 'material-react-table';
import TableLoader from '../../components/table/TableLoader';
import { useTableData } from '../../hooks/useTableData';

const Faults = () => {
  const {
    data: faults,
    loading,
    error,
  } = useTableData<Fault>({
    fetchData: async () => {
      const result = (await getFaults()) as FaultsResponse;
      return result.items as Fault[];
    },
  });

  const columns = useMemo<MRT_ColumnDef<Partial<Fault>>[]>(
    () => [
      {
        accessorKey: 'direccionPoblacion',
        header: 'Direction',
        size: 150,
      },
      {
        accessorKey: 'estado',
        header: 'Status',
        size: 150,
      },
      {
        accessorKey: 'contactoNombre',
        header: 'Name',
        size: 150,
      },
      {
        accessorKey: 'contactoTelefono',
        header: 'Telefono',
        size: 200,
      },
    ],
    []
  );

  return (
    <Fragment>
      {loading && <TableLoader count={9} />}
      {error && <p>{error}</p>}
      {!loading && !error && (
        <MaterialReactTable columns={columns} data={faults} />
      )}
    </Fragment>
  );
};

export default Faults;
