import { useEffect, useState } from 'react';
import cx from 'clsx';
import { Center, Pagination, ScrollArea, Table } from '@mantine/core';
import classes from './AirportTable.module.css';
import { getAirports } from '@lib/airport.ts';
import { Airport } from '@lib/airport.types.ts';

export function AirportTable() {
  const [data, setData] = useState<Airport[]>([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const limit = 1000;
    getAirports({ page, limit }).then((r) => {
      setData(r.data);
      setTotalPages(r.total / r.data.length);
    });
  }, [page]);

  const rows = data.map((row, idx) => (
    <Table.Tr key={idx}>
      <Table.Td>{row.name}</Table.Td>
      <Table.Td>{row.icao}</Table.Td>
      <Table.Td>{row.latitude}</Table.Td>
      <Table.Td>{row.longitude}</Table.Td>
    </Table.Tr>
  ));

  return (
    <>
      <ScrollArea h={300} onScrollPositionChange={({ y }) => setScrolled(y !== 0)}>
        <Table miw={700}>
          <Table.Thead className={cx(classes.header, { [classes.scrolled]: scrolled })}>
            <Table.Tr>
              <Table.Th>Name</Table.Th>
              <Table.Th>ICAO</Table.Th>
              <Table.Th>Latitude</Table.Th>
              <Table.Th>Longitude</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>{rows}</Table.Tbody>
        </Table>
      </ScrollArea>
      <Center mt='sm'>
        <Pagination value={page} onChange={setPage} total={totalPages} siblings={1} boundaries={1} />
      </Center>
    </>
  );
}
