import { useState } from 'react'
import { IRegion } from '../interfaces/fuel'
import { useRegions, useServers } from '../hooks/swrHooks'
import { useDebounce } from '@uidotdev/usehooks'
import { Autocomplete, CloseButton, Table } from '@mantine/core'

export default function ServersView() {
    const [search, setSearch] = useState<string | undefined>("")

    const debouncedSearch = useDebounce(search, 500)

    const [selectedOption, setSelectedOption] = useState<number | null>(null)

    const { regions } = useRegions(10, 1, debouncedSearch)

    const { servers } = useServers(selectedOption, 0, 10)

    const serversColumns = [
        //{ field: 'id', headerName: 'ID', type: "number" },
        {
            field: 'name', headerName: 'Название', type: "string", editable: true,
        },
        {
            field: 'region_id',
            editable: true,
            headerName: 'region_id',
            flex: 1
        }
    ]

    return (
        <>
            <form>
                <Autocomplete
                    placeholder="Район"
                    flex={'1'}
                    data={regions ? regions.map((item: IRegion) => ({ label: item.name, value: item.id.toString() })) : []}
                    onSelect={(e) => console.log(e.currentTarget.value)}
                    onChange={(value) => setSearch(value)}
                    onOptionSubmit={(value) => setSelectedOption(Number(value))}
                    rightSection={
                        search !== '' && (
                            <CloseButton
                                size="sm"
                                onMouseDown={(event) => event.preventDefault()}
                                onClick={() => {
                                    setSearch('')
                                    setSelectedOption(null)
                                }}
                                aria-label="Clear value"
                            />
                        )
                    }
                    value={search}
                />
            </form>


            <Table highlightOnHover>
                <Table.Thead>
                    <Table.Tr>
                        {serversColumns.map(column => (
                            <Table.Th key={column.field}>{column.headerName}</Table.Th>
                        ))}
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    <Table.Tr>
                        {serversColumns.map(column => (
                            <Table.Td key={column.field}>{servers ? servers[column.field] : ''}</Table.Td>
                        ))}
                    </Table.Tr>
                </Table.Tbody>
            </Table>
        </>
    )
}