import {
  Alert,
  Box,
  Button,
  Divider,
  Flex,
  Modal,
  notifier,
  Typography
} from '@tidbcloud/uikit'
import { Form, FormSelect } from '@tidbcloud/uikit/biz'
import { IconCheckCircle } from '@tidbcloud/uikit/icons'
import { AxiosResponse } from 'axios'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

import { useUpdateRegionOpsAuditLogSettings } from 'apiClient/services/devops'
import {
  TenantCommonResp,
  TenantRegion
} from 'apiClient/services/devops/interface'

import {
  maxAgeDefaultOptions,
  maxAgeDisabledOptions,
  maxSizeDefaultOptions,
  LogSettingDefaultValues
} from './helper'
// import { getErrorMessage } from 'utils/error'

interface LogSettingsProps {
  opened: boolean
  isUpdate?: boolean
  tenantId: string
  regionLogicalName: string
  onCancel: () => void
  onPrevious?: () => void
  config?: TenantRegion
  onConfirm?: (res: AxiosResponse<TenantCommonResp>) => Promise<void>
}

interface LogSettingsFormData {
  fileSizeLimitInMb: string
  rotationIntervalInMin: string
}

export const LogSettingsModal = ({
  opened,
  isUpdate,
  onCancel,
  onPrevious,
  config,
  onConfirm,
  tenantId,
  regionLogicalName
}: LogSettingsProps) => {
  const form = useForm<LogSettingsFormData>({
    defaultValues: {
      fileSizeLimitInMb:
        config?.ops_audit_log_setting?.log_rotation?.file_size_limit_in_mb?.toString() ??
        LogSettingDefaultValues.logRotation.fileSizeLimitInMb.toString(),
      rotationIntervalInMin:
        config?.ops_audit_log_setting?.log_rotation?.rotation_interval_in_min?.toString() ??
        LogSettingDefaultValues.logRotation.rotationIntervalInMin.toString()
    }
  })

  const { mutateAsync: updateSettings, isLoading } =
    useUpdateRegionOpsAuditLogSettings()

  const [loading, setLoading] = useState(false)

  const formSelectBaseStyles = (theme: any) => ({
    root: {
      flex: 1
    },
    section: {
      '&[data-position="left"]': {
        color: theme.colors.carbon[9],
        borderRight: `1px solid ${theme.colors.carbon[4]}`,
        backgroundColor: theme.colors.carbon[2],
        marginRight: 10
      }
    },
    input: {
      flex: 1
    }
  })

  const maxAgeSeconds = [...maxAgeDisabledOptions, ...maxAgeDefaultOptions]

  const onSubmit = async (data: LogSettingsFormData) => {
    try {
      setLoading(true)

      const res = await updateSettings({
        tenantId,
        data: {
          enabled: true,
          region_logical_name: regionLogicalName,
          reason: isUpdate ? 'Update audit log settings' : 'Enable audit log',
          log_rotation: {
            file_size_limit_in_mb: parseInt(data.fileSizeLimitInMb),
            rotation_interval_in_min: parseInt(data.rotationIntervalInMin)
          },
          log_location: config?.ops_audit_log_setting?.log_location
        }
      })
      notifier.success(
        <>
          Your operation is submitted successfully. Waiting for approval. You
          can click{' '}
          <a
            target="_blank"
            rel="noreferrer"
            href={`/operations/${res.data.instance_id}`}
          >
            operation detail
          </a>{' '}
          to check the progress.
        </>,
        { autoClose: 10000 }
      )
      await onConfirm?.(res)
      form.reset()
      setLoading(false)
    } catch (_e) {
      setLoading(false)
    }
  }

  const onClose = () => {
    form.reset()
    onCancel()
  }

  useEffect(() => {
    if (config?.ops_audit_log_setting) {
      form.setValue(
        'fileSizeLimitInMb',
        config.ops_audit_log_setting.log_rotation?.file_size_limit_in_mb &&
          config.ops_audit_log_setting.log_rotation?.file_size_limit_in_mb !== 0
          ? config.ops_audit_log_setting.log_rotation?.file_size_limit_in_mb?.toString()
          : LogSettingDefaultValues.logRotation.fileSizeLimitInMb.toString()
      )
      form.setValue(
        'rotationIntervalInMin',
        config.ops_audit_log_setting.log_rotation?.rotation_interval_in_min?.toString() ??
          LogSettingDefaultValues.logRotation.rotationIntervalInMin.toString()
      )
    }
  }, [config, form])

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title={
        isUpdate ? 'Edit OPS Audit Log Settings' : 'Enable OPS Audit Logging'
      }
      size={800}
    >
      <Form
        layout="none"
        form={form}
        withActions={false}
        onSubmit={onSubmit}
        onCancel={onClose}
        stopPropagation
      >
        <Box>
          {!isUpdate && (
            <Alert color="green" mb={24} icon={<IconCheckCircle />}>
              The connection is successfully
            </Alert>
          )}

          <Typography variant="label-lg" mb={8}>
            Log File Rotation
          </Typography>
          <Flex gap={16}>
            <FormSelect
              name="fileSizeLimitInMb"
              leftSectionWidth={112}
              leftSection="File Size Limit"
              styles={(theme) => ({
                ...formSelectBaseStyles(theme),
                input: {
                  paddingLeft: 126
                }
              })}
              rules={{
                required: 'File Size Limit is required'
              }}
              data={maxSizeDefaultOptions}
            />

            <FormSelect
              name="rotationIntervalInMin"
              leftSectionWidth={132}
              leftSection="Rotation Interval"
              data={maxAgeSeconds}
              rules={{
                required: 'Rotation Interval is required'
              }}
              styles={(theme) => ({
                ...formSelectBaseStyles(theme),
                input: {
                  paddingLeft: 146
                }
              })}
            />
          </Flex>

          {/* {error && (
            <Form.ErrorMessage mt={8} message={getErrorMessage(error) || ''} />
          )} */}

          <Divider mx={-24} my={24} />

          <Flex gap={16} justify="flex-end">
            <Button variant="default" onClick={onCancel}>
              Cancel
            </Button>

            {!isUpdate && (
              <Button variant="default" onClick={() => onPrevious?.()}>
                Previous
              </Button>
            )}

            <Button type="submit" loading={loading}>
              Save {isUpdate ? '' : 'and Enable'}
            </Button>
          </Flex>
        </Box>
      </Form>
    </Modal>
  )
}
