import { IconMathMax, IconPlus, IconTableMinus } from "@tabler/icons-react";
import { FuelExpenseDtoHeaders, FuelLimitDtoHeaders } from "../dto/fuel/fuel.dto";
import useSWR from "swr";
import { fetcher } from "../http/axiosInstanceNest";
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";

import { AgGridReact } from "ag-grid-react";
import { AllCommunityModule, ColDef, ModuleRegistry } from 'ag-grid-community'
import { CalendarStrings, DatePicker, defaultDatePickerStrings } from "@fluentui/react-datepicker-compat"
import { Button, Dialog, DialogSurface, DialogTitle, DialogTrigger, Field, Input, Spinner, Tab, TabList } from "@fluentui/react-components";

ModuleRegistry.registerModules([AllCommunityModule])

type FieldType = 'text' | 'number' | 'select' | 'date'

interface IPostInclude {
    field: string
    field_type: FieldType
}

interface ITableSchema {
    label: string
    value: string
    get: string
    post: string
    headers: { [key: string]: string }
    post_include: IPostInclude[]
    icon: JSX.Element
}

export default function FuelPage() {
    const tables: ITableSchema[] = [
        {
            label: 'Расходы',
            value: 'expenses',
            get: '/fuel/expenses',
            post: '/fuel/expenses',
            headers: FuelExpenseDtoHeaders,
            post_include: [
                {
                    field: 'id_boiler',
                    field_type: 'text'
                },
                {
                    field: 'id_fuel',
                    field_type: 'text'
                },
                {
                    field: 'date',
                    field_type: 'date'
                },
                {
                    field: 'value',
                    field_type: 'text'
                }
            ],
            icon: <IconTableMinus size={12} />
        },
        {
            label: 'Лимиты',
            value: 'limits',
            get: '/fuel/limits',
            post: '/fuel/limits',
            headers: FuelLimitDtoHeaders,
            post_include: [
                {
                    field: 'id_boiler',
                    field_type: 'text'
                },
                {
                    field: 'id_fuel',
                    field_type: 'text'
                },
                {
                    field: 'month',
                    field_type: 'number'
                },
                {
                    field: 'year',
                    field_type: 'number'
                },
                {
                    field: 'value',
                    field_type: 'text'
                }
            ],
            icon: <IconMathMax size={12} />,
        }
    ]

    const [currentTab, setCurrentTab] = useState(tables[0])

    const { data, isLoading } = useSWR(currentTab.get, () => fetcher(currentTab.get), { revalidateOnFocus: false })

    return (
        <>
            <div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
                <TabList defaultValue={tables[0].value} selectedValue={currentTab.value}>
                    {tables.map((table, index) => (
                        <Tab key={index} value={table.value} icon={table.icon} onClick={() => setCurrentTab(table)}>
                            {table.label}
                        </Tab>
                    ))}
                </TabList>

                <div style={{ display: 'flex', padding: '1rem' }}>
                    <Dialog>
                        <DialogTrigger>
                            <Button
                                appearance='primary'
                                icon={<IconPlus />}
                                style={{ flexShrink: 0 }}
                            >
                                Добавить
                            </Button>
                        </DialogTrigger>

                        <DialogSurface>
                            <DialogTitle>Добавление объекта</DialogTitle>
                            <ModalCreate currentTab={currentTab} />
                        </DialogSurface>
                    </Dialog>
                </div>

                <div style={{
                    width: '100%',
                    height: '100%',
                }}>
                    {tables.map((table, index) => {
                        if (table.value === currentTab.value) {
                            return (
                                isLoading ?
                                    <div style={{ display: 'flex', width: '100%', justifyContent: 'center', padding: '1rem' }}>
                                        <Spinner />
                                    </div>
                                    :
                                    <div style={{  width: 'auto', height: '100%', padding: '1rem' }}>
                                        <AgGridReact
                                            key={index}
                                            // rowData={[
                                            //     Object.keys(table.headers).reduce((obj, key) => ({ ...obj, [key]: 'test1' }), {}),
                                            //     Object.keys(table.headers).reduce((obj, key) => ({ ...obj, [key]: 'test' }), {})
                                            // ]}
                                            rowData={data}
                                            columnDefs={Object.keys(table.headers).map((header) => ({
                                                field: header
                                            })) as ColDef[]}
                                            defaultColDef={{
                                                flex: 1,
                                            }}
                                        />
                                    </div>
                            )
                        }
                    }
                    )}
                </div>

            </div>
        </>
    )
}

const ModalCreate = ({
    currentTab
}: {
    currentTab: ITableSchema
}) => {
    const { register, handleSubmit,
        //formState: { errors, isSubmitting, dirtyFields, isValid }
    } = useForm({
        mode: 'onChange',
    })

    const onSubmit: SubmitHandler<any> = async (values: any) => {
        console.log('Values to submit:', values)
    }

    const localizedStrings: CalendarStrings = {
        ...defaultDatePickerStrings,
        days: [
            'Воскресенье',
            'Понедельник',
            'Вторник',
            'Среда',
            'Четверг',
            'Пятница',
            'Суббота'
        ],
        shortDays: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
        months: [
            "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Ноябрь", "Декабрь"
        ],
        shortMonths: [
            "Янв",
            "Фев",
            "Мар",
            "Апр",
            "Май",
            "Июн",
            "Июл",
            "Авг",
            "Сен",
            "Ноя",
            "Дек",
        ]
    }

    return (
        <form style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }} onSubmit={handleSubmit(onSubmit)}>
            {currentTab.post_include.map((header, index) => {
                switch (header.field_type) {
                    case 'date':
                        return (
                            <Field key={index} label={header.field}>
                                <DatePicker
                                    strings={localizedStrings}
                                    {...register(header.field, {
                                        required: true
                                    })} />
                            </Field>
                        )
                    case 'text':
                        return (
                            <Field key={index} label={header.field}>
                                <Input {...register(header.field, {
                                    required: true
                                })} />
                            </Field>
                        )
                    default:
                        return (
                            <Field key={index} label={header.field}>
                                <Input {...register(header.field, {
                                    required: true
                                })} />
                            </Field>
                        )
                }
            })}

            <Button style={{ marginTop: '2rem' }} appearance="primary" type='submit'>
                Добавить
            </Button>
        </form>
    )
}