import {
  Input,
  Box,
  Card,
  Group,
  Select,
  Tooltip,
  ActionIcon,
  Textarea,
  Flex,
  Typography,
  openConfirmModal,
  notifier
} from '@tidbcloud/uikit'
import { CodeBlock, Form } from '@tidbcloud/uikit/biz'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

import { useRequestSupport } from 'dbaas/screens/HelpCenter/RequestSupport/helper'
import { usePatchEndpoint } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'

import NumberInputWithTip from '../common/NumberInputWithTip'
import { useDataApiContext } from '../context'
import { showErrorMsg } from '../helpers'
import { EndPoint } from '../types'

import CodeExample from './CodeExample'

type Chat2queryEndpointProps = {
  timeout: number
  rows: number
}

const Chat2queryEndpoint = () => {
  const { orgId, projectId, appList, appListRef, setAppList, editEndpoint, editEndpointRef, setEditEndpoint } =
    useDataApiContext()
  const {
    store: { currentCluster }
  } = useStores()
  const { open } = useRequestSupport()

  const updateEndpoint = usePatchEndpoint()
  const [codeExampleModalOpened, setCodeExampleModalOpened] = useState(false)

  const form = useForm<Chat2queryEndpointProps>({
    mode: 'onChange',
    defaultValues: {
      timeout: editEndpoint?.settings?.timeout || 0,
      rows: editEndpoint?.settings?.row_limit || 0
    }
  })

  const {
    setValue,
    watch,
    formState: { isValid }
  } = form

  const timeout = watch('timeout')
  const rows = watch('rows')

  useEffect(() => {
    if (!editEndpoint) {
      return
    }

    setValue('rows', editEndpoint?.settings?.row_limit || 0)
    setValue('timeout', editEndpoint?.settings?.timeout || 0)
  }, [editEndpoint?.id, editEndpoint?.settings])

  const onSubmit = () => {
    openConfirmModal({
      title: 'Confirm to save',
      centered: true,
      children: (
        <Typography>
          The changes will apply to <b>{editEndpoint?.name}</b> immediately.
        </Typography>
      ),
      labels: {
        confirm: 'Confirm',
        cancel: 'Cancel'
      },
      onCancel: () => {},
      onConfirm: async () => {
        await updateEndpoint
          .mutateAsync({
            orgId,
            projectId,
            appId: `${editEndpoint?.dataappp_id}`,
            endpointId: `${editEndpoint?.id}`,
            data: {
              settings: {
                row_limit: rows,
                timeout
              }
            }
          })
          .then((res) => {
            if (res.code !== 200) {
              notifier.error(res.message, {
                autoClose: 3000
              })
              return
            }

            const endp = {
              ...(editEndpoint as EndPoint),
              settings: {
                row_limit: rows,
                timeout: timeout
              }
            }
            setEditEndpoint(endp)
            editEndpointRef.current = endp
            const apps = appList.slice()
            const app = apps.find((app) => `${app.id}` === `${editEndpoint?.dataappp_id}`)
            if (app) {
              const endpoint = (app.endpoints || []).find((endp) => `${endp.id}` === `${editEndpoint?.id}`)
              if (endpoint) {
                endpoint.settings = {
                  row_limit: rows,
                  timeout: timeout
                }
                setAppList(apps)
                appListRef.current = apps
              }
            }
          })
          .catch((err) => {
            showErrorMsg(err)
          })
      }
    })
  }

  return (
    <Box
      sx={{
        padding: '16px 24px',
        flex: 1,
        maxWidth: 2000,
        overflow: 'auto'
      }}
    >
      <Typography variant="headline-md">{editEndpoint?.name}</Typography>

      <Card sx={{ width: '100%', marginTop: 24 }} shadow="none" radius="md" withBorder>
        <Flex>
          <Typography variant="headline-sm">Properties</Typography>
          <Tooltip
            multiline
            w={400}
            label={`This DataAPI endpoint is part of a system data application, and the only editable ${
              editEndpoint?.type === 'chat2eda' ? 'property is "Timeout"' : 'properties are "Timeout" and "Max Rows"'
            }.`}
            color="dark"
            withArrow
            arrowPosition="center"
            arrowSize={6}
          >
            <ActionIcon aria-hidden c="carbon.9" variant="transparent">
              <IconInfoCircle size={14} />
            </ActionIcon>
          </Tooltip>
        </Flex>

        <Typography variant="title-md" fw={600} mb={4} mt={16}>
          Path
        </Typography>
        <Input sx={{ minWidth: '100px' }} value={editEndpoint?.endpoint} disabled />

        <Group gap="xs" mb={4} mt={16} align="center">
          <Typography variant="title-md" fw={600}>
            Endpoint URL
          </Typography>

          <Typography
            variant="action-sm"
            data-mp-event="DataService code example clicked"
            data-mp-source="chat2data endpoint"
            component="a"
            onClick={() => setCodeExampleModalOpened(true)}
          >
            Show Code Example
          </Typography>
        </Group>
        <CodeBlock>{`${editEndpoint?.service_url || ''}${editEndpoint?.endpoint}`}</CodeBlock>

        <Box
          component="div"
          mt={16}
          sx={() => ({
            position: 'relative'
          })}
        >
          <Form
            form={form}
            onSubmit={onSubmit}
            actionsProps={{
              cancelText: '',
              confirmText: 'Save',
              confirmProps: {
                'data-mp-event': 'mp-save-1691461015011',
                h: 32,
                disabled:
                  !isValid ||
                  (rows === editEndpoint?.settings?.row_limit && timeout === editEndpoint?.settings?.timeout),
                loading: updateEndpoint.isLoading
              }
            }}
            formMode="onSubmit"
          >
            <Flex gap={16} align="flex-start">
              <Select
                data={[
                  {
                    label: 'POST',
                    value: 'POST'
                  },
                  {
                    label: 'GET',
                    value: 'GET'
                  },
                  {
                    label: 'DELETE',
                    value: 'DELETE'
                  },
                  {
                    label: 'PUT',
                    value: 'PUT'
                  }
                ]}
                label={
                  <Typography variant="title-md" fw={600} mb={4}>
                    Request Method
                  </Typography>
                }
                size="xs"
                disabled
                value={editEndpoint?.method || 'POST'}
              ></Select>

              <NumberInputWithTip
                label={
                  <Typography variant="title-md" fw={600} mb={4}>
                    Timeout(ms)
                  </Typography>
                }
                name="timeout"
                defaultValue={5000}
                min={1}
                max={120000}
                tooltips="The value must be in the range of 1-120000"
              />

              {editEndpoint?.type !== 'chat2eda' && (
                <NumberInputWithTip
                  label={
                    <Typography variant="title-md" fw={600} mb={4}>
                      Max Rows
                    </Typography>
                  }
                  name="rows"
                  defaultValue={1000}
                  min={1}
                  max={2000}
                  tooltips="The value must be in the range of 1-2000"
                />
              )}
            </Flex>

            <Typography variant="title-md" fw={600} mb={4} mt={16}>
              Description
            </Typography>
            <Textarea
              styles={{
                input: { lineHeight: '20px' }
              }}
              autosize
              disabled
              value={decodeURIComponent(editEndpoint?.description || '')}
            />

            <Typography
              variant="body-lg"
              sx={() => ({
                position: 'absolute',
                left: 0,
                bottom: 4,
                marginRight: 80,
                marginTop: 16
              })}
            >
              The limit for requests is 100 times per day. For a higher quota, please{' '}
              <Typography
                variant="action-md"
                component="span"
                sx={{ cursor: 'pointer' }}
                fw={400}
                onClick={() => {
                  open({
                    orgId,
                    cluster: currentCluster || undefined
                  })
                }}
              >
                contact us
              </Typography>
              .
            </Typography>
          </Form>
        </Box>
      </Card>

      <CodeExample default={codeExampleModalOpened} onClose={() => setCodeExampleModalOpened(false)} />
    </Box>
  )
}

export default Chat2queryEndpoint
