import {
    ActionIcon,
    ActionIconGroup,
    Button,
    Group,
    Modal,
    Stack,
    TextInput,
    Tooltip
} from '@mantine/core'
import { CreateInternalSquadCommand } from '@remnawave/backend-contract'
import { TbCirclesRelation, TbPlus, TbRefresh } from 'react-icons/tb'
import { useDisclosure } from '@mantine/hooks'
import { useTranslation } from 'react-i18next'
import { useField } from '@mantine/form'

import { QueryKeys, useCreateInternalSquad, useGetInternalSquads } from '@shared/api/hooks'
import { MODALS, useModalsStoreOpenWithData } from '@entities/dashboard/modal-store'
import { UniversalSpotlightActionIconShared } from '@shared/ui/universal-spotlight'
import { BaseOverlayHeader } from '@shared/ui/overlays/base-overlay-header'
import { HelpActionIconShared } from '@shared/ui/help-drawer'
import { queryClient } from '@shared/api'

interface IProps {
    internalSquadCount: number
}

export const InternalSquadsHeaderActionButtonsFeature = (props: IProps) => {
    const { internalSquadCount } = props

    const { t } = useTranslation()
    const { isFetching } = useGetInternalSquads()

    const openModalWithData = useModalsStoreOpenWithData()

    const [opened, { open, close }] = useDisclosure(false)

    const handleUpdate = async () => {
        await queryClient.refetchQueries({
            queryKey: QueryKeys.internalSquads.getInternalSquads.queryKey
        })
    }

    const nameField = useField<CreateInternalSquadCommand.Request['name']>({
        initialValue: '',
        validateOnChange: true,
        validate: (value) => {
            const result = CreateInternalSquadCommand.RequestSchema.omit({
                inbounds: true
            }).safeParse({ name: value })
            return result.success ? null : result.error.errors[0]?.message
        }
    })
    const { mutate: createInternalSquad, isPending } = useCreateInternalSquad({
        mutationFns: {
            onSuccess: (data) => {
                close()
                nameField.reset()
                handleUpdate()

                openModalWithData(MODALS.INTERNAL_SQUAD_SHOW_INBOUNDS, {
                    squadUuid: data.uuid
                })
            },

            onError: (error) => {
                nameField.setError(error.message)
            }
        }
    })

    return (
        <Group grow preventGrowOverflow={false} wrap="wrap">
            <HelpActionIconShared hidden={false} screen="PAGE_INTERNAL_SQUADS" />

            {internalSquadCount > 0 && <UniversalSpotlightActionIconShared />}

            <ActionIconGroup>
                <Tooltip label={t('common.update')} withArrow>
                    <ActionIcon
                        loading={isFetching}
                        onClick={handleUpdate}
                        size="input-md"
                        variant="soft"
                    >
                        <TbRefresh size="24px" />
                    </ActionIcon>
                </Tooltip>
            </ActionIconGroup>

            <ActionIconGroup>
                <Tooltip
                    label={t('internal-squad-header-action-buttons.feature.create-internal-squad')}
                    withArrow
                >
                    <ActionIcon color="teal" onClick={open} size="input-md" variant="soft">
                        <TbPlus size="24px" />
                    </ActionIcon>
                </Tooltip>
            </ActionIconGroup>

            <Modal
                centered
                onClose={close}
                opened={opened}
                size="md"
                title={
                    <BaseOverlayHeader
                        iconColor="teal"
                        IconComponent={TbCirclesRelation}
                        iconVariant="soft"
                        title={t(
                            'internal-squad-header-action-buttons.feature.create-internal-squad'
                        )}
                    />
                }
            >
                <form
                    onSubmit={(e) => {
                        e.preventDefault()
                        createInternalSquad({
                            variables: {
                                name: nameField.getValue(),
                                inbounds: []
                            }
                        })
                    }}
                >
                    <Stack gap="md">
                        <TextInput
                            data-autofocus
                            label={t('internal-squad-header-action-buttons.feature.squad-name')}
                            placeholder={t(
                                'internal-squad-header-action-buttons.feature.enter-squad-name'
                            )}
                            required
                            {...nameField.getInputProps()}
                        />
                        <Group justify="flex-end">
                            <Button color="gray" onClick={close} variant="soft">
                                {t('common.cancel')}
                            </Button>

                            <Button
                                color="teal"
                                disabled={!!nameField.error || nameField.getValue().length === 0}
                                loading={isPending}
                                type="submit"
                                variant="default"
                            >
                                {t('common.create')}
                            </Button>
                        </Group>
                    </Stack>
                </form>
            </Modal>
        </Group>
    )
}
