import {
    Collapse,
    Divider,
    Group,
    NumberInput,
    Stack,
    Switch,
    TagsInput,
    Text
} from '@mantine/core'
import { CreateNodeCommand, UpdateNodeCommand } from '@remnawave/backend-contract'
import { ForwardRefComponent, HTMLMotionProps, Variants } from 'motion/react'
import { TbChartBar, TbChartLine } from 'react-icons/tb'
import { UseFormReturnType } from '@mantine/form'
import { useTranslation } from 'react-i18next'
import { PiTagDuotone } from 'react-icons/pi'
import { useState } from 'react'

import { SelectInfraProviderShared } from '@shared/ui/infra-billing/select-infra-provider/select-infra-provider.shared'
import { BaseOverlayHeader } from '@shared/ui/overlays/base-overlay-header'
import { SectionCard } from '@shared/ui/section-card'
import { useGetNodesTags } from '@shared/api/hooks'

interface IProps<T extends CreateNodeCommand.Request | UpdateNodeCommand.Request> {
    cardVariants: Variants
    form: UseFormReturnType<T>
    motionWrapper: ForwardRefComponent<HTMLDivElement, HTMLMotionProps<'div'>>
}

export const NodeTrackingAndBillingCard = <
    T extends CreateNodeCommand.Request | UpdateNodeCommand.Request
>(
    props: IProps<T>
) => {
    const { t } = useTranslation()
    const { data: nodesTags } = useGetNodesTags()
    const { cardVariants, form, motionWrapper } = props

    const [advancedOpened, setAdvancedOpened] = useState<boolean>(false)

    form.watch('isTrafficTrackingActive', ({ value }) => {
        setAdvancedOpened(value ?? false)
    })

    const MotionWrapper = motionWrapper

    return (
        <MotionWrapper variants={cardVariants}>
            <SectionCard.Root>
                <SectionCard.Section>
                    <BaseOverlayHeader
                        iconColor="yellow"
                        IconComponent={TbChartBar}
                        iconVariant="soft"
                        title={t('base-node-form.tracking-and-billing')}
                        titleOrder={5}
                    />
                </SectionCard.Section>
                <SectionCard.Section>
                    <Stack gap="md">
                        <SelectInfraProviderShared
                            selectedInfraProviderUuid={form.getValues().providerUuid}
                            setSelectedInfraProviderUuid={(providerUuid) => {
                                form.setValues({
                                    providerUuid
                                } as Partial<T>)
                                form.setTouched({
                                    providerUuid: true
                                })
                                form.setDirty({
                                    providerUuid: true
                                })
                            }}
                        />

                        <Stack gap={0}>
                            <Group gap="xs" justify="space-between">
                                <Group gap="xs">
                                    <TbChartLine
                                        size={18}
                                        style={{ color: 'var(--mantine-color-indigo-6)' }}
                                    />
                                    <Text fw={500} size="sm">
                                        {t('base-node-form.traffic-tracking')}
                                    </Text>
                                </Group>
                                <Switch
                                    key={form.key('isTrafficTrackingActive')}
                                    {...form.getInputProps('isTrafficTrackingActive', {
                                        type: 'checkbox'
                                    })}
                                    onChange={(event) => {
                                        form.getInputProps('isTrafficTrackingActive').onChange(
                                            event
                                        )
                                        setAdvancedOpened(event.currentTarget.checked)
                                    }}
                                    size="md"
                                />
                            </Group>

                            <Collapse in={advancedOpened}>
                                <Stack gap="sm" mt="sm">
                                    <Divider size="xs" />
                                    <Group gap="md" grow justify="space-between" w="100%">
                                        <NumberInput
                                            allowDecimal={false}
                                            decimalScale={0}
                                            defaultValue={0}
                                            hideControls
                                            key={form.key('trafficLimitBytes')}
                                            label={t('base-node-form.limit')}
                                            leftSection={
                                                <>
                                                    <Text
                                                        display="flex"
                                                        size="0.75rem"
                                                        style={{ justifyContent: 'center' }}
                                                        ta="center"
                                                        w={26}
                                                    >
                                                        GB
                                                    </Text>
                                                    <Divider orientation="vertical" />
                                                </>
                                            }
                                            thousandSeparator=","
                                            {...form.getInputProps('trafficLimitBytes')}
                                            styles={{
                                                label: { fontWeight: 500 }
                                            }}
                                        />

                                        <NumberInput
                                            key={form.key('trafficResetDay')}
                                            label={t('base-node-form.reset-day')}
                                            {...form.getInputProps('trafficResetDay')}
                                            allowDecimal={false}
                                            allowNegative={false}
                                            clampBehavior="strict"
                                            decimalScale={0}
                                            hideControls
                                            max={31}
                                            min={1}
                                            placeholder={t('base-node-form.e-g-1-31')}
                                            styles={{
                                                label: { fontWeight: 500 }
                                            }}
                                        />

                                        <NumberInput
                                            key={form.key('notifyPercent')}
                                            label={t('base-node-form.notify-percent')}
                                            {...form.getInputProps('notifyPercent')}
                                            allowDecimal={false}
                                            allowNegative={false}
                                            clampBehavior="strict"
                                            decimalScale={0}
                                            hideControls
                                            max={100}
                                            placeholder={t('base-node-form.e-g-50')}
                                            styles={{
                                                label: {
                                                    fontWeight: 500,
                                                    whiteSpace: 'nowrap',
                                                    textOverflow: 'ellipsis'
                                                }
                                            }}
                                        />
                                    </Group>
                                </Stack>
                            </Collapse>
                        </Stack>

                        <TagsInput
                            clearable
                            data={nodesTags?.tags || []}
                            key={form.key('tags')}
                            label="Tags"
                            leftSection={<PiTagDuotone size="16px" />}
                            maxTags={10}
                            placeholder="Enter tags (comma, space, semicolon)"
                            splitChars={[',', ' ', ';']}
                            {...form.getInputProps('tags')}
                            error={
                                Object.keys(form.errors)
                                    .filter((key) => key.startsWith('tags.'))
                                    .map((key) => form.errors[key])
                                    .join(', ') || form.getInputProps('tags').error
                            }
                        />
                    </Stack>
                </SectionCard.Section>
            </SectionCard.Root>
        </MotionWrapper>
    )
}
