import { Button, Flex, Typography, Box, Card, Group, HoverCard, notifier } from '@tidbcloud/uikit'
import { Form, FormSelect, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useMemo } from 'react'
import { useForm } from 'react-hook-form'

import { useGetChat2QuerySettings, useUpdateChat2QuerySettings } from 'dbaas/services/dataservice'
import { DtoChat2QuerySettings } from 'dbaas/services/dataservice/interface'
import useStores from 'dbaas/stores/useStores'

import { useDataApiContext } from '../../context'
import { showErrorMsg } from '../../helpers'

export const Chat2Query = observer(() => {
  const {
    store: { tenantData, activeProject }
  } = useStores()

  const { editApp } = useDataApiContext()

  const form = useForm<DtoChat2QuerySettings>({
    defaultValues: {
      language_code: 'English',
      llm_api_key: '',
      llm_model: 'claude3-sonnet'
    }
  })

  const languageCode = form.watch('language_code')

  const llmApiKey = form.watch('llm_api_key')

  const llmModel = form.watch('llm_model')

  const { data, refetch, isLoading } = useGetChat2QuerySettings(
    tenantData?.id || '',
    activeProject.id,
    editApp?.id || '',
    {
      query: {
        enabled: !!tenantData?.id && !!activeProject.id && !!editApp?.id,
        refetchOnWindowFocus: false,
        onSuccess: (values) => {
          form.setValue('language_code', values?.data?.language_code)
          form.setValue('llm_api_key', values?.data?.llm_api_key || '')
          form.setValue('llm_model', values?.data?.llm_model)
        }
      }
    }
  )

  const valueChanged = useMemo(
    () =>
      languageCode !== data?.data?.language_code ||
      ((data?.data?.llm_api_key || llmApiKey) && llmApiKey !== data?.data?.llm_api_key) ||
      llmModel !== data?.data?.llm_model,
    [languageCode, llmApiKey, llmModel, data]
  )

  const { mutateAsync, isLoading: isSubmiting } = useUpdateChat2QuerySettings()

  const handleSubmit = async (values: DtoChat2QuerySettings) => {
    try {
      if (values.llm_api_key === data?.data?.llm_api_key) {
        values.llm_api_key = null
      }
      const resp = await mutateAsync({
        orgId: tenantData.id || '',
        projectId: activeProject.id,
        appId: editApp?.id || '',
        data: values
      })
      if (resp.code === 200) {
        notifier.success('Chat2Query setting update successful')
        await refetch()
      } else {
        notifier.error(resp.message)
      }
    } catch (e) {
      showErrorMsg(e)
    }
  }

  return (
    <Form<DtoChat2QuerySettings> form={form} withActions={false} onSubmit={handleSubmit}>
      <Card p={24} mt={24} sx={{ overflow: 'visible' }}>
        <Flex justify="space-between" align="center" mb={16}>
          <Box sx={{ whiteSpace: 'break-spaces' }}>
            <Typography variant="title-md" mb={4}>
              Chat2Query
            </Typography>
          </Box>
          <Button
            size="compact-xs"
            h={28}
            variant="default"
            type="submit"
            data-mp-event="Update chat2Query clicked"
            data-mp-source="dataapp"
            disabled={!valueChanged || isLoading}
            loading={isSubmiting}
          >
            Update
          </Button>
        </Flex>
        <Group gap={24}>
          <FormSelect
            name="llm_model"
            data={[
              { label: 'Opus', value: 'claude3-opus', disabled: !llmApiKey },
              { label: 'Sonnet', value: 'claude3-sonnet' },
              { label: 'Haiku', value: 'claude3-haiku' },
              { label: 'gpt-4', value: 'gpt-4', disabled: !llmApiKey },
              { label: 'gpt-4o', value: 'gpt-4o' },
              { label: 'gpt-4o-mini', value: 'gpt-4o-mini' }
            ]}
            sx={{ flex: 1 }}
            label={
              <Group gap={4}>
                LLM Model
                <HoverCard withArrow shadow="md" position="top" width={300}>
                  <HoverCard.Dropdown>
                    Select LLM Chat2Query's to use(Note: Without an llm_api_key, you can't use claude3-opus and gpt-4).
                    Options include claude3-opus/claude3-sonnet/claude3-haiku/gpt-4/gpt-4o/gpt-4o-mini
                  </HoverCard.Dropdown>
                  <HoverCard.Target>
                    <IconInfoCircle size={14} />
                  </HoverCard.Target>
                </HoverCard>
              </Group>
            }
          />
          <FormTextInput
            name="llm_api_key"
            label={
              <Group gap={4}>
                LLM Key
                <HoverCard withArrow shadow="md" position="top" width={300}>
                  <HoverCard.Dropdown>
                    Your LLM service access key(Optional: Without setting this, you're limited to 100 queries/day. Set
                    your llm_api_key to bypass query limits or leave blank for system-provided access with model
                    restrictions.).
                  </HoverCard.Dropdown>
                  <HoverCard.Target>
                    <IconInfoCircle size={14} />
                  </HoverCard.Target>
                </HoverCard>
              </Group>
            }
            sx={{ flex: 1 }}
          />
          <FormSelect
            name="language_code"
            data={[
              { label: 'English', value: 'English' },
              { label: 'Chinese', value: 'Chinese' }
            ]}
            sx={{ flex: 1 }}
            label={
              <Group gap={4}>
                Preferred Language
                <HoverCard withArrow shadow="md" position="top" width={300}>
                  <HoverCard.Dropdown>
                    Select Chat2Query's language. Choose from 'English' or 'Chinese'
                  </HoverCard.Dropdown>
                  <HoverCard.Target>
                    <IconInfoCircle size={14} />
                  </HoverCard.Target>
                </HoverCard>
              </Group>
            }
          />
        </Group>
      </Card>
    </Form>
  )
})
