import { Box, Typography } from '@mui/material'
import { DataGrid, GridColDef } from '@mui/x-data-grid'
import { useEffect, useState } from 'react'
import { IBoiler } from '../interfaces/fuel'
import { useBoilers } from '../hooks/swrHooks'

function Boilers() {
    const [boilersPage, setBoilersPage] = useState(1)
    const [boilerSearch, setBoilerSearch] = useState("")
    const [debouncedBoilerSearch, setDebouncedBoilerSearch] = useState("")
    const { boilers } = useBoilers(10, boilersPage, debouncedBoilerSearch)

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedBoilerSearch(boilerSearch)
        }, 500)

        return () => {
            clearTimeout(handler)
        }
    }, [boilerSearch])

    useEffect(() => {
        setBoilersPage(1)
        setBoilerSearch("")
    }, [])

    const boilersColumns: GridColDef[] = [
        { field: 'id', headerName: 'ID', type: "number" },
        { field: 'boiler_name', headerName: 'Название', type: "string" },
        { field: 'boiler_code', headerName: 'Код', type: "string" },
        { field: 'id_city', headerName: 'Город', type: "string" },
        { field: 'activity', headerName: 'Активен', type: "boolean" },
    ]

    return (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px', height: '100%' }}>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px', height: '100%', p: '16px' }}>
                <Typography variant='h6' fontWeight='600'>
                    Котельные
                </Typography>

                {boilers &&
                    <DataGrid
                        rows={boilers.map((boiler: IBoiler) => {
                            return { ...boiler, id: boiler.id_object }
                        })}
                        columns={boilersColumns}
                    />
                }

            </Box>
        </Box>
    )
}

export default Boilers