import { Alert, Button, Group, LoadingOverlay, notifier, Stack, Typography } from '@tidbcloud/uikit'
import { FormNumberInput, FormSelect } from '@tidbcloud/uikit/biz'
import { FormProvider, useForm } from 'react-hook-form'
import { Link } from 'react-router-dom'

import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useOrgProjectClusterIds } from 'dbaas/features/Common'
import {
  useServerlessServiceGetCluster,
  useServerlessServicePartialUpdateCluster
} from 'dbaas/services/api-clients/v2023/serverless/v1beta1'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { getUTCString } from 'dbaas/utils/format'

import { times, toLocalBackupTime, toUTCBackupTime, useNextBackupTimeTip } from './utils'

const defaultValues = {
  backup_time: '00:00',
  retention_period: 30
}

export function BackupSettingServerless({
  closeModal,
  shareCluster
}: {
  closeModal: () => void
  shareCluster: SharedCluster
}) {
  const {
    store: { tenantData }
  } = useStores()
  const methods = useForm({ defaultValues })
  const { handleSubmit, watch, setValue } = methods
  const backupTime = watch('backup_time')

  const { orgId, projectId, clusterId } = useOrgProjectClusterIds()
  const { data, isFetching } = useServerlessServiceGetCluster(
    clusterId!,
    {
      view: 'FULL',
      orgId,
      projectId
    },
    {
      query: {
        refetchOnWindowFocus: false,
        onSuccess(data) {
          setValue('retention_period', data.automatedBackupPolicy?.retentionDays ?? defaultValues.retention_period)
          setValue(
            'backup_time',
            toLocalBackupTime(data.automatedBackupPolicy?.startTime ?? defaultValues.backup_time, tenantData.timezone)
          )
        }
      }
    }
  )
  const isZeroSpendingLimit = data?.spendingLimit?.monthly === 0
  const isStarterCluster = shareCluster.computed.isStarter
  const isEssentialCluster = shareCluster.computed.isEssential
  const disableEdit = !isEssentialCluster && isZeroSpendingLimit

  const mutation = useServerlessServicePartialUpdateCluster()
  const onSubmit = async (data: typeof defaultValues) => {
    if (isZeroSpendingLimit) {
      closeModal()
      return
    }

    try {
      await mutation.mutateAsync({
        clusterId: clusterId!,
        data: {
          updateMask: 'automatedBackupPolicy',
          cluster: {
            automatedBackupPolicy: {
              startTime: toUTCBackupTime(data.backup_time, tenantData.timezone),
              retentionDays: data.retention_period
            }
          }
        },
        params: {
          orgId,
          projectId
        }
      })
      notifier.success('Backup settings saved successfully.')
      closeModal()
    } catch (e) {
      notifier.error(getErrorMessage(e))
    }
  }

  return (
    <FormProvider {...methods}>
      <form onSubmit={handleSubmit(onSubmit)} data-testid="backup-setting-serverless">
        <LoadingOverlay
          visible={isFetching}
          data-testid="backup-setting-serverless-loading-overlay"
          overlayProps={{ blur: 2 }}
        />
        <Stack>
          <Group>
            <Typography variant="label-lg" w={200}>
              Backup Cycle
            </Typography>
            <Typography>Daily</Typography>
          </Group>

          <Group>
            <Typography variant="label-lg" w={200}>
              Backup Retention
            </Typography>

            <FormNumberInput
              name="retention_period"
              min={1}
              max={30}
              size="xs"
              w={160}
              disabled={disableEdit}
              suffix=" Day(s)"
            />
          </Group>

          <Group>
            <Typography variant="label-lg" w={200}>
              Backup Time
            </Typography>
            <FormSelect name="backup_time" data={times} size="xs" w={160} disabled={disableEdit} />
            <Typography variant="body-md">{getUTCString(tenantData.timezone)}</Typography>
          </Group>

          <Alert>
            {useNextBackupTimeTip(tenantData.timezone, backupTime)}

            {isStarterCluster && isZeroSpendingLimit && (
              <>
                {' '}
                <Link to={`/clusters/${clusterId}/edit-spendlimit`}>Set up spending limit</Link> to personalize your
                backup setting.
              </>
            )}
          </Alert>
        </Stack>

        <Group justify="flex-end" mt={16}>
          <Button
            variant="default"
            type="button"
            data-mp-event="Serverless Backup Setting Modal Cancel Button Clicked"
            onClick={closeModal}
          >
            Cancel
          </Button>
          {!disableEdit && (
            <Button
              type="submit"
              loading={mutation.isLoading}
              data-mp-event="Serverless Backup Setting Modal Confirm Button Clicked"
            >
              Confirm
            </Button>
          )}
        </Group>
      </form>
    </FormProvider>
  )
}
