import { Button, Combobox, Dialog, DialogActions, DialogBody, DialogContent, DialogSurface, DialogTitle, DialogTrigger, Field, Input, Option, Tab, TabList, Text } from '@fluentui/react-components'
import useSWR from 'swr'
import axios from 'axios'
import { AgGridReact } from 'ag-grid-react'
import { Controller, SubmitHandler, useForm } from 'react-hook-form'
import { useState } from 'react'
import { FuelType } from '../../../interfaces/fuel'

type Inputs = {
    id_fuel_type: string
    name: string
}

const FuelsPage = () => {
    const [selectedIdFuels, setSelectedIdFuels] = useState<number | null>(null)

    const { data: fuelTypes } = useSWR('/fuel/fuel-types', () => axios.get(`/fuel/fuel-types`, {
        baseURL: import.meta.env.VITE_API_NEST_URL
    }).then(res => {
        setSelectedIdFuels(res.data[0].id)
        return res.data
    }))

    const { data: fuels, mutate: mutateFuels, isLoading: fuelsLoading } = useSWR(selectedIdFuels ? `/fuel/fuels?id_fuels=${selectedIdFuels}` : null, () => axios.get(`/fuel/fuels?id_fuels=${selectedIdFuels}`, {
        baseURL: import.meta.env.VITE_API_NEST_URL
    }).then(res => res.data))

    const {
        register,
        handleSubmit,
        control,
        //formState: { errors, isSubmitting },
    } = useForm<Inputs>()

    const onSubmit: SubmitHandler<Inputs> = (data) => {
        console.log(data)
        mutateFuels([...fuels, data])

        setTimeout(() => {
            console.log("done")
        }, 1000)
    }

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            padding: '1rem',
            width: '100%',
            gap: '1rem'
        }}>
            <div style={{
                display: 'flex',
                width: '100%',
                flexDirection: 'column',
                gap: '1rem'
            }}>
                <Text size={600} weight='bold'>
                    Виды топлива
                </Text>

                <Dialog>
                    <DialogTrigger>
                        <Button appearance='primary' style={{ width: 'min-content' }}>
                            Добавить
                        </Button>
                    </DialogTrigger>

                    <DialogSurface>
                        {fuelTypes &&
                            <form onSubmit={handleSubmit(onSubmit)} >
                                <DialogBody>
                                    <DialogTitle>Добавление вида топлива</DialogTitle>

                                    <DialogContent style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                                        <Controller
                                            name='id_fuel_type'
                                            control={control}
                                            rules={{
                                                required: true
                                            }}
                                            render={({ field: { value, onChange } }) => {
                                                return (
                                                    <Field label={'Тип топлива'}>
                                                        <Combobox
                                                            autoFocus
                                                            placeholder="Тип топлива"
                                                            clearable
                                                            value={fuelTypes.find((f: {
                                                                id: number
                                                                name: string
                                                            }) => f.id.toString() == value)?.name || ''}
                                                            size='medium'
                                                            onOptionSelect={(_, data) => {
                                                                onChange(data.optionValue)
                                                                //onValueChange(data.optionValue === '' || data.optionValue === undefined ? null : data.optionValue)
                                                            }}
                                                        >
                                                            {fuelTypes && Array.isArray(fuelTypes) && fuelTypes.map((option) => (
                                                                <Option key={`fuel-type-${option.id}`} text={option.name} value={option.id}>
                                                                    {option.name}
                                                                </Option>
                                                            ))}
                                                        </Combobox>
                                                    </Field>

                                                );
                                            }}
                                        />

                                        <Field label={'Наименование'}>
                                            <Input {...register('name', { required: true })} />
                                        </Field>
                                    </DialogContent>

                                    <DialogActions>
                                        <Button type='submit' appearance='primary'>
                                            Добавить
                                        </Button>
                                    </DialogActions>
                                </DialogBody>
                            </form>
                        }

                    </DialogSurface>
                </Dialog>
            </div>

            {fuelTypes && Array.isArray(fuelTypes) &&
                <TabList selectedValue={selectedIdFuels} onTabSelect={(_, data) => {
                    setSelectedIdFuels(Number(data.value))
                }}>
                    {fuelTypes && Array.isArray(fuelTypes) && fuelTypes.map((ft: FuelType) => (
                        <Tab id={ft.id.toString()} value={ft.id} key={ft.id}>
                            {ft.name}
                        </Tab>
                    ))
                    }
                </TabList>}

            <AgGridReact
                key={`fuels`}
                loading={fuelsLoading}
                overlayLoadingTemplate='Загрузка...'
                overlayNoRowsTemplate='Нет данных'
                rowData={fuels}
                columnDefs={[
                    {
                        field: 'name',
                        headerName: 'Наименование'
                    },
                    {
                        field: 'tnt',
                        headerName: 'Перевод в натуральный показатель'
                    },
                    {
                        field: 'tut',
                        headerName: 'Перевод в условный показатель'
                    },
                    {
                        field: 'koef',
                        headerName: 'Коэффициент'
                    },
                    {
                        field: 'Gk',
                        headerName: 'Гк'
                    },
                    // {
                    //     field: 'id_fuels',
                    //     headerName: 'Вид топлива',
                    //     editable: true,
                    //     cellEditor: FuelTypeEditor,
                    //     cellRenderer: FuelTypeRenderer,
                    //     enableCellChangeFlash: true
                    // },
                ]}
                defaultColDef={{
                    flex: 1,
                }}
            />
        </div >
    )
}

export default FuelsPage