import { Fragment, useEffect, useMemo, useState } 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';

const Faults = () => {
  const [faults, setFaults] = useState<Fault[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  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,
      },
    ],
    []
  );

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const data = (await getFaults()) as FaultsResponse;
        setFaults(data.items);
      } catch (error) {
        console.error(error);
        setError('Error fetching data');
      }
      setLoading(false);
    };

    fetchData();
  }, []);

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

export default Faults;
