import { Loader, Flex, Modal, Typography } from '@tidbcloud/uikit'
import { Form, FormSelect, FormSwitch } from '@tidbcloud/uikit/biz'
import React, { useState } from 'react'

import { sqlEditorRowsSetting, useGetSqlEditorRowsSetting } from 'dbaas/services'
import { eventTracking } from 'dbaas/utils/tracking'

import { useSQLEditorContext } from '../context/editor-context'

type FormValues = {
  limit: string
  show_system_db_schema: boolean
  systemShow: boolean
}

export const Settings: React.FC<React.PropsWithChildren<{ defaultVisible?: boolean; onClose?: () => void }>> = ({
  defaultVisible = false,
  onClose = () => {}
}) => {
  const [visible, setVisible] = useState(defaultVisible)
  const { sqlLimit, setSqlLimit, systemShow, setSystemShow, clusterId, orgId, projectId } = useSQLEditorContext()

  const closeModal = () => {
    setVisible(false)
    onClose()
  }

  const { isLoading, isRefetching } = useGetSqlEditorRowsSetting(orgId, projectId, clusterId, {
    query: {
      enabled: visible && !!orgId && !!projectId && !!clusterId,
      refetchInterval: false,
      refetchOnWindowFocus: false,
      onSuccess: (res) => {
        const data = res.data || {}
        setSqlLimit(data.limit || 500)
        setSystemShow(data.show_system_db_schema || false)
      }
    }
  })

  const saveSettings = async (values: any) => {
    const params = {
      limit: parseInt(values.limit),
      show_system_db_schema: values.systemShow
    }

    eventTracking('SQL Editor Settings Confirm Button Clicked', params)

    const res = await sqlEditorRowsSetting(orgId, projectId, clusterId, params)

    if (res.code !== 200) {
      return
    }

    setSqlLimit(values.limit)
    setSystemShow(values.systemShow)

    closeModal()
  }

  return (
    <Modal
      size={400}
      opened={visible}
      centered={true}
      title="SQL Editor Settings"
      children={
        <Form<FormValues>
          defaultValues={{
            limit: `${sqlLimit}`,
            systemShow: systemShow
          }}
          errorMessageProps={{
            onDismiss: undefined
          }}
          actionsProps={{
            confirmText: 'Save'
          }}
          layout="none"
          onSubmit={saveSettings}
          onCancel={closeModal}
        >
          <Flex align="center" justify="space-between" pb={16}>
            <Typography variant="body-lg" fw={600}>
              Result row limit
            </Typography>
            <FormSelect
              name="limit"
              size="xs"
              w={100}
              data={[
                {
                  label: '500',
                  value: '500'
                },
                {
                  label: '1000',
                  value: '1000'
                },
                {
                  label: '2000',
                  value: '2000'
                }
              ]}
            />
          </Flex>
          <Flex align="center" justify="space-between" pt={16} pb={16}>
            <Typography variant="body-lg" fw={600}>
              Show system database schema
            </Typography>
            {isLoading || isRefetching ? <Loader size="sm" /> : <FormSwitch name="systemShow" size="md" />}
          </Flex>
        </Form>
      }
      onClose={closeModal}
    />
  )
}

export default Settings
