import {
  Modal,
  Typography,
  Flex,
  ActionIcon,
  ActionIconProps,
  Stack
} from '@tidbcloud/uikit'
import { Form, FormSwitch } from '@tidbcloud/uikit/biz'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { ReactNode, useEffect } from 'react'
import React from 'react'
import { useForm } from 'react-hook-form'

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

type FormValuesType = { enabled: boolean }

export const SettingsButton: React.FC<React.PropsWithChildren<IType>> = ({
  orgId,
  enabled,
  buttonProps,
  text,
  handler,
  onConfirm
}: IType) => {
  const [opened, modalHandlers] = useDisclosure()

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

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

  // const { mutateAsync } = useUpdateAuditLogSettings()

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

  const handleOpen = () => {
    modalHandlers.open()
    form.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
        styles={{ body: { padding: 0 } }}
        centered
        title="Console Audit Logging Settings"
        size={700}
        opened={opened}
        onClose={modalHandlers.close}
      >
        <Form
          form={form}
          actionsProps={{
            p: '0 24px 24px 0',
            confirmProps: {
              disabled: true
            }
          }}
          onCancel={modalHandlers.close}
          onSubmit={() => {}}
        >
          <Stack p="xl" gap={4}>
            <Flex align="flex-end">
              <Typography variant="title-lg">
                {enabled ? 'Disable' : 'Enable'} console audit logs
              </Typography>
              <FormSwitch
                disabled
                data-testid="setting-switch"
                ml="auto"
                height={20}
                name="enabled"
              />
            </Flex>
            <Typography variant="body-lg">
              System will track all console behaviors and operations for this
              organization.
            </Typography>
          </Stack>
        </Form>
      </Modal>
    </>
  )
}
