import { cleanChanges, getChanges, Mode, setMode, useMapStore } from '../../store/map'
import { IconCropLandscape, IconCropPortrait, IconEdit, IconEye, IconPrinter } from '@tabler/icons-react'
import { useEffect, useState } from 'react'
import { PrintOrientation, setPrintOrientation, usePrintStore } from '../../store/print'
import { Button, Menu, MenuItemRadio, MenuList, MenuPopover, MenuProps, MenuTrigger, SplitButton } from '@fluentui/react-components'
import axiosInstance from '../../http/axiosInstanceNest'

const MapMode = ({
    map_id
}: { map_id: string }) => {
    const { mode, changes, currentChange } = useMapStore().id[map_id]

    const { printOrientation } = usePrintStore()

    const [checkedValues, setCheckedValues] = useState<Record<string, string[]>>({ orientation: [printOrientation] })

    const onChange: MenuProps["onCheckedValueChange"] = (
        _,
        { name, checkedItems }
    ) => {
        setCheckedValues((s) => ({ ...s, [name]: checkedItems }))
        setPrintOrientation(checkedItems[0] as PrintOrientation)
        setMode(map_id, 'print' as Mode)
    }

    useEffect(() => {
        if (printOrientation) {
            setCheckedValues((s) => ({ ...s, ['orientation']: [printOrientation] }))
        }
    }, [printOrientation])

    return (
        <div style={{
            display: 'flex',
            gap: '0.25rem',
            padding: '0.25rem',
            zIndex: 1,
            background: 'var(--colorNeutralBackground1)',
            borderRadius: 'var(--borderRadiusMedium)'
        }}>
            <Button
                appearance={mode === 'view' ? 'primary' : 'subtle'}
                key={'view'}
                onClick={() => {
                    setMode(map_id, 'view' as Mode)
                }}
                icon={<IconEye size={16} />}
            //mod={{ active: mode === 'view' as Mode }}
            >
                Просмотр
            </Button>

            <Button
                appearance={mode === 'edit' ? 'primary' : 'subtle'}
                key={'edit'}
                onClick={() => {
                    setMode(map_id, 'edit' as Mode)
                }}
                icon={<IconEdit size={16} />}
            //mod={{ active: mode === 'edit' as Mode }}
            >
                Редактирование
            </Button>

            <Menu checkedValues={checkedValues} onCheckedValueChange={onChange}>
                <MenuTrigger>
                    <SplitButton
                        appearance={mode === 'print' ? 'primary' : 'subtle'}
                        primaryActionButton={{
                            onClick: () => setMode(map_id, 'print' as Mode)
                        }}
                        icon={<IconPrinter size={16} />}
                    >
                        Печать
                    </SplitButton>
                </MenuTrigger>

                <MenuPopover>
                    <MenuList>
                        <MenuItemRadio name='orientation' value='horizontal' icon={<IconCropLandscape style={{ display: 'block' }} />}>
                            Горизонтальная
                        </MenuItemRadio>
                        <MenuItemRadio name='orientation' value='vertical' icon={<IconCropPortrait style={{ display: 'block' }} />}>
                            Вертикальная
                        </MenuItemRadio>
                    </MenuList>
                </MenuPopover>
            </Menu>

            {changes && currentChange && mode === 'edit' && <Button
                appearance={mode === 'edit' ? 'primary' : 'subtle'}
                key={'save'}
                // onClick={async () => {
                //     setMode(map_id, 'edit' as Mode)

                //     const changes = getChanges(map_id).get(currentChange)

                //     if (changes) {
                //         await axiosInstance.post(`/gis/features/update`, {
                //             features: changes
                //         },
                //             {
                //                 baseURL: import.meta.env.VITE_API_NEST_URL,
                //             }).then(() => {
                //                 cleanChanges(map_id)
                //             })
                //     }
                // }}
                onClick={async () => {
                    setMode(map_id, 'edit' as Mode);

                    const changes = getChanges(map_id);
                    const latestChanges = new Map();

                    // Process ALL changes in the map
                    for (const change of changes.values()) {
                        if (Array.isArray(change)) {
                            change.forEach(c => {
                                if (c.object_id) {
                                    latestChanges.set(c.object_id, c);
                                }
                            });
                        } else if (change.object_id) {
                            latestChanges.set(change.object_id, change);
                        }
                    }

                    const featuresToUpdate = Array.from(latestChanges.values());

                    if (featuresToUpdate.length > 0) {
                        await axiosInstance.post(`/gis/features/update`, {
                            features: featuresToUpdate
                        }, {
                            baseURL: import.meta.env.VITE_API_NEST_URL,
                        }).then(() => {
                            cleanChanges(map_id); // This clears the entire map
                        });
                    }
                }}
                icon={<IconEdit size={16} />}
            //mod={{ active: mode === 'edit' as Mode }}
            >
                Сохранить
            </Button>}
        </div >
    )
}

export default MapMode