import { AppBar, Autocomplete, Box, CircularProgress, Dialog, Grid, IconButton, TextField, Toolbar } from '@mui/material'
import { Fragment, useEffect, useState } from 'react'
import { IRegion } from '../interfaces/fuel'
import { useRegions, useServers, useServersInfo } from '../hooks/swrHooks'
import FullFeaturedCrudGrid from './TableEditable'
import ServerService from '../services/ServersService'
import { GridColDef, GridRenderCellParams } from '@mui/x-data-grid'
import { Close, Cloud, CloudOff } from '@mui/icons-material'
import ServerData from './ServerData'
import { IServersInfo } from '../interfaces/servers'
import CardInfo from './CardInfo/CardInfo'
import CardInfoLabel from './CardInfo/CardInfoLabel'
import CardInfoChip from './CardInfo/CardInfoChip'
import { useDebounce } from '@uidotdev/usehooks'

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

    const debouncedSearch = useDebounce(search, 500)

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

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

    const { serversInfo } = useServersInfo(selectedOption?.id)

    const [serverDataOpen, setServerDataOpen] = useState(false)
    const [currentServerData, setCurrentServerData] = useState<any | null>(null)

    useEffect(() => {
        if (regions) {
            setOptions([...regions])
        }
    }, [regions])

    const { servers, isLoading: serversLoading } = useServers(selectedOption?.id, 0, 10)

    const serversColumns: GridColDef[] = [
        //{ field: 'id', headerName: 'ID', type: "number" },
        {
            field: 'name', headerName: 'Название', type: "string", editable: true,
        },
        {
            field: 'region_id',
            editable: true,
            renderCell: (params) => (
                <div>
                    {params.value}
                </div>
            ),
            renderEditCell: (params: GridRenderCellParams) => (
                <Autocomplete
                    sx={{ display: 'flex', flexGrow: '1' }}
                    onInputChange={(_, value) => setSearch(value)}
                    onChange={(_, value) => {
                        params.value = value
                    }}
                    isOptionEqualToValue={(option: IRegion, value: IRegion) => option.name === value.name}
                    getOptionLabel={(option: IRegion) => option.name ? option.name : ""}
                    options={options}
                    loading={isLoading}
                    value={params.value}
                    renderInput={(params) => (
                        <TextField
                            {...params}
                            size='small'
                            variant='standard'
                            label="Район"
                            InputProps={{
                                ...params.InputProps,
                                endAdornment: (
                                    <Fragment>
                                        {isLoading ? <CircularProgress color="inherit" size={20} /> : null}
                                        {params.InputProps.endAdornment}
                                    </Fragment>
                                )
                            }}
                        />
                    )}
                />
            ),
            width: 200
        }
    ]

    return (
        <>
            <Dialog
                fullScreen
                open={serverDataOpen}
                onClose={() => {
                    setServerDataOpen(false)
                }}
                aria-labelledby="modal-modal-title"
                aria-describedby="modal-modal-description">
                <AppBar sx={{ position: 'sticky' }}>
                    <Toolbar>
                        <IconButton
                            edge="start"
                            color="inherit"
                            onClick={() => {
                                setServerDataOpen(false)
                            }}
                            aria-label="close"
                        >
                            <Close />
                        </IconButton>
                    </Toolbar>
                </AppBar>

                {currentServerData &&
                    <ServerData
                        id={currentServerData?.id}
                        region_id={currentServerData?.region_id}
                        name={currentServerData?.name}
                    />
                }
            </Dialog>

            {serversInfo &&
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px', height: '100%' }}>
                    <Grid container spacing={{ xs: 2, md: 3 }} columns={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4 }}>
                        {serversInfo.map((serverInfo: IServersInfo) => (
                            <Grid key={`si-${serverInfo.id}`} item xs={1} sm={1} md={1}>
                                <CardInfo label={serverInfo.name}>
                                    <CardInfoLabel label='Количество IP' value={serverInfo.IPs_count} />
                                    <CardInfoLabel label='Количество серверов' value={serverInfo.servers_count} />
                                    <CardInfoChip
                                        status={serverInfo.status === "Online"}
                                        label={serverInfo.status}
                                        iconOn={<Cloud />}
                                        iconOff={<CloudOff />}
                                    />
                                </CardInfo>
                            </Grid>
                        ))}
                    </Grid>
                </Box>
            }

            <FullFeaturedCrudGrid
                loading={serversLoading}
                autoComplete={
                    <Autocomplete
                        onInputChange={(_, value) => setSearch(value)}
                        onChange={(_, value) => setSelectedOption(value)}
                        isOptionEqualToValue={(option: IRegion, value: IRegion) => option.id === value.id}
                        getOptionLabel={(option: IRegion) => option.name ? option.name : ""}
                        options={options}
                        loading={isLoading}
                        value={selectedOption}
                        renderInput={(params) => (
                            <TextField
                                {...params}
                                size='small'
                                label="Район"
                                InputProps={{
                                    ...params.InputProps,
                                    endAdornment: (
                                        <Fragment>
                                            {isLoading ? <CircularProgress color="inherit" size={20} /> : null}
                                            {params.InputProps.endAdornment}
                                        </Fragment>
                                    )
                                }}
                            />
                        )}
                    />
                }
                onSave={() => {
                }}
                onDelete={ServerService.removeServer}
                initialRows={servers}
                columns={serversColumns}
                actions
                onRowClick={(params) => {
                    setCurrentServerData(params.row)
                    setServerDataOpen(true)
                }}
            />
        </>
    )
}