import useSWR from 'swr'
import { fetcher } from '../../http/axiosInstance'
import { BASE_URL } from '../../constants'
import { Checkbox, Divider, Flex, Grid, Stack, Text } from '@mantine/core'
import { IObjectParam, IParam } from '../../interfaces/objects'
import { decodeDoubleEncodedString } from '../../utils/format'
import TCBParameter from './TCBParameter'

interface ObjectParameterProps {
    showLabel?: boolean,
    param: IObjectParam,
}

const ObjectParameter = ({
    param,
    showLabel = true
}: ObjectParameterProps) => {
    const { data: paramData } = useSWR(
        `/general/params/all?param_id=${param.id_param}`,
        (url) => fetcher(url, BASE_URL.ems).then(res => res[0] as IParam),
        {
            revalidateOnFocus: false
        }
    )

    const Parameter = (type: string, name: string, value: unknown, vtable: string) => {
        switch (type) {
            case 'bit':
                return (
                    <Flex direction='row' align='center' gap='sm'>
                        <Checkbox defaultChecked={value as boolean} />
                        <Text>{name}</Text>
                    </Flex>
                )
            case 'varchar(200)':
                return (
                    <Text>
                        {decodeDoubleEncodedString(value as string)}
                    </Text>
                )
            case 'varchar(5)':
                return (
                    <Text>
                        {decodeDoubleEncodedString(value as string)}
                    </Text>
                )
            case 'bigint':
                return (
                    <Text>
                        {(value as string)}
                    </Text>
                )
            case 'GTCB':
                return (
                    <TCBParameter value={value as string} vtable={vtable} />
                )
            case 'TCB':
                return (
                    <TCBParameter value={value as string} vtable={vtable} />
                )
            default:
                return (
                    <div>
                        {type}
                    </div>
                )
        }
    }

    return (
        <>
            {paramData &&
                <Stack gap={0}>
                    {showLabel &&
                        <Divider my="xs" label={paramData.name} labelPosition="left" />
                    }
                    {Parameter(paramData.format, paramData.name, param.value, paramData.vtable)}
                </Stack>
            }
        </>
    )
}

export default ObjectParameter