import { Checkbox, ComboboxData, Grid, NumberInput, Select, Text, Textarea } from '@mantine/core';
import useSWR from 'swr';
import { fetcher } from '../../http/axiosInstance';
import { BASE_URL } from '../../constants';
import { useObjectsStore } from '../../store/objects';

interface TableValueProps {
    name: string;
    value: unknown;
    type: 'value' | 'boolean' | 'number' | 'select' | 'string';
    unit?: string | null | undefined;
    vtable?: string;
}

const TableValue = ({
    name,
    value,
    type,
    unit,
    vtable
}: TableValueProps) => {
    const { selectedDistrict } = useObjectsStore()

    //Get available values
    const { data: tcbAll, isValidating } = useSWR(
        type === 'select' && selectedDistrict ? `/general/params/tcb?vtable=${vtable}&id_city=${selectedDistrict}` : null,
        (url) => fetcher(url, BASE_URL.ems).then(res => {
            if (Array.isArray(res)) {
                return res.map((el) => ({
                    label: el.name || "",
                    value: JSON.stringify(el.id)
                })) as ComboboxData
            }
        }),
        {
            revalidateOnFocus: false,
            revalidateIfStale: false
        }
    )

    return (
        <Grid>
            <Grid.Col span={4} style={{ display: 'flex', alignItems: 'center' }}>
                <Text size='xs' style={{ textWrap: 'wrap' }}>{name as string}</Text>
            </Grid.Col>
            <Grid.Col span={8}>
                {type === 'boolean' ?
                    <Checkbox defaultChecked={value as boolean} />
                    :
                    type === 'number' ?
                        <NumberInput
                            size='xs'
                            value={value as number}
                            onChange={() => { }}
                            suffix={unit ? ` ${unit}` : ''}
                        />
                        :
                        type === 'select' && !isValidating && tcbAll ?
                            <Select size='xs' data={tcbAll} defaultValue={JSON.stringify(value)} />
                            :
                            type === 'string' ?
                                <Textarea size='xs' defaultValue={value as string} autosize minRows={1} />
                                :
                                <Text size='xs'>{value as string}</Text>
                }
            </Grid.Col>
        </Grid>
    )
}

export default TableValue