import { Modal, Typography, ActionIcon, ActionIconProps, Stack, Group, Button } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { observer } from 'mobx-react'
import { ReactNode, useEffect } from 'react'
import React from 'react'
import { useForm } from 'react-hook-form'

import { useUpdateSettings } from 'dbaas/services'
import useStores from 'dbaas/stores/useStores'

interface IType {
  enabled: boolean
  buttonProps?: ActionIconProps
  text?: string | ReactNode
  handler?: ReactNode
  onConfirm?: () => void
}

type FormValuesType = { enabled: boolean }

const SettingsButton: React.FC<React.PropsWithChildren<IType>> = ({
  enabled,
  buttonProps,
  text,
  handler,
  onConfirm
}: IType) => {
  const {
    store: { tenantData }
  } = useStores()

  const [opened, modalHandlers] = useDisclosure()

  const form = useForm<FormValuesType>({ defaultValues: { enabled } })
  const { setValue } = form

  useEffect(() => setValue('enabled', enabled), [enabled, setValue])

  const { mutateAsync, isLoading } = useUpdateSettings()

  const handleSubmit = async (values: FormValuesType) => {
    await mutateAsync({
      orgId: tenantData.id,
      data: { status: +values.enabled }
    })
    modalHandlers.close()
    onConfirm?.()
  }

  const handleOpen = () => {
    modalHandlers.open()
    setValue('enabled', enabled)
  }

  return (
    <>
      <div onClick={handleOpen}>
        {handler || (
          <ActionIcon {...buttonProps} size={40} data-mp-event="Settings Button clicked" data-testid="auditlog-setting">
            {text}
          </ActionIcon>
        )}
      </div>
      <Modal centered withCloseButton={false} size={640} opened={opened} onClose={modalHandlers.close}>
        <Stack gap={32}>
          <Stack gap={16}>
            <Typography variant="headline-md">{enabled ? 'Disable' : 'Enable'} Console Audit Logging</Typography>
            <Typography variant="body-lg">
              {enabled
                ? 'When disabled, the system will no longer track all console behaviors and operations for this organization. This may introduce potential audit gaps. previously collected logs will hidden , but not be deleted.'
                : 'When enabled, the system will track all console behaviors and operations for this organization.'}
            </Typography>
          </Stack>
          <Group justify="flex-end">
            <Button type="button" variant="default" onClick={modalHandlers.close}>
              Cancel
            </Button>
            <Button
              type="button"
              variant={enabled ? 'outline' : 'filled'}
              color={enabled ? 'red' : 'carbon'}
              loading={isLoading}
              onClick={() => handleSubmit({ enabled: !enabled })}
            >
              {enabled ? 'Disable' : 'Enable'}
            </Button>
          </Group>
        </Stack>
      </Modal>
    </>
  )
}

export default observer(SettingsButton)
