import { Button, Divider, Group, HoverCard, Modal, Stack, TextInput, Typography, notifier } from '@tidbcloud/uikit'
import { IconAlertTriangle, IconInfoCircle } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'

import { useRegionServiceUpdateByocVcpuPool } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { getErrorMessage } from 'dbaas/services/errorCodes'

import { PoolNameTag } from './PoolNameTag'

interface VCPULimitModalProps {
  currentLimit?: number | string
  orgId: string
  opened: boolean
  poolName: string
  projectId: string
  resourcePoolId?: string
  onClose: () => void
  onSuccess?: () => void
}

export const VCPULimitModal = ({
  currentLimit,
  orgId,
  opened,
  poolName,
  projectId,
  resourcePoolId,
  onClose,
  onSuccess
}: VCPULimitModalProps) => {
  const currentLimitValue = currentLimit == null ? '' : String(currentLimit)
  const [newLimit, setNewLimit] = useState(currentLimitValue)
  const updateByocVcpuPool = useRegionServiceUpdateByocVcpuPool()

  useEffect(() => {
    if (opened) {
      setNewLimit(currentLimitValue)
    }
  }, [currentLimitValue, opened])

  const parsedNewLimit = Number(newLimit)
  const isNewLimitValid = Number.isInteger(parsedNewLimit) && parsedNewLimit > 0

  const handleUpdate = async () => {
    if (!resourcePoolId || !isNewLimitValid) return

    try {
      await updateByocVcpuPool.mutateAsync({
        resourcePoolId,
        data: {
          vcpusLimit: String(parsedNewLimit)
        },
        params: {
          orgId,
          projectId
        }
      })
      notifier.success('vCPU pool limit updated successfully.')
      onSuccess?.()
      onClose()
    } catch (error) {
      notifier.error(getErrorMessage(error, true))
    }
  }

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      centered
      size={580}
      padding={0}
      title={
        <Group gap="sm">
          <PoolNameTag poolName={poolName} />
          <Typography variant="title-lg">Update Limit</Typography>
        </Group>
      }
    >
      <Stack gap={0}>
        <Stack gap="xl">
          <Stack gap="md">
            <Typography variant="label-md">Current Maximum Pool vCPU Limit</Typography>
            <Typography variant="title-lg" c="carbon.9">
              {currentLimitValue || '-'}
            </Typography>
          </Stack>

          <Stack gap="sm">
            <Group gap={6} align="center">
              <Typography variant="label-md">New Limit</Typography>
              <HoverCard width={520}>
                <HoverCard.Dropdown>
                  The limit controls autoscaling and manual TiKV/TiFlash scaling for the resource pool.
                </HoverCard.Dropdown>
                <HoverCard.Target>
                  <IconInfoCircle size={18} color="var(--mantine-color-carbon-6)" />
                </HoverCard.Target>
              </HoverCard>
            </Group>
            <TextInput
              value={newLimit}
              onChange={(event) => setNewLimit(event.currentTarget.value)}
              error={
                newLimit && !isNewLimitValid ? (
                  <Typography variant="body-sm" c="red.7">
                    Enter a positive integer
                  </Typography>
                ) : undefined
              }
              size="lg"
            />
          </Stack>

          <Group
            align="flex-start"
            gap="sm"
            wrap="nowrap"
            p="md"
            bg="yellow.1"
            sx={(theme) => ({
              borderLeft: `3px solid ${theme.colors.yellow[7]}`
            })}
          >
            <IconAlertTriangle size={22} color="var(--mantine-color-yellow-7)" />
            <Typography variant="body-lg" c="yellow.9">
              The new limit must be greater than or equal to the current provisioned vCPU. Otherwise, the update will be
              rejected.
            </Typography>
          </Group>
        </Stack>

        <Divider />
        <Group justify="flex-end" pt="xl">
          <Button variant="default" onClick={onClose}>
            Cancel
          </Button>
          <Button
            onClick={handleUpdate}
            loading={updateByocVcpuPool.isLoading}
            disabled={!resourcePoolId || !isNewLimitValid}
          >
            Update
          </Button>
        </Group>
      </Stack>
    </Modal>
  )
}
