import { Button, Flex, Typography, Box, Card, Modal, TextInput, CopyButton, Tooltip, HoverCard } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { IconDataService, IconXClose, IconCopy03, IconInfoCircle } from '@tidbcloud/uikit/icons'
import { encode } from 'js-base64'
import { useEffect, useState } from 'react'

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

const GptIntegration = ({
  onOpenApiKeyModal,
  copyedKey,
  title,
  logo,
  desc,
  onClose
}: {
  copyedKey?: string
  title: string
  desc: string
  logo: React.ReactNode
  onOpenApiKeyModal: () => void
  onClose: () => void
}) => {
  const [opened, { open, close }] = useDisclosure(false)
  const { editApp } = useDataApiContext()
  const [encodedKey, setEncodedKey] = useState('')
  const [apiKey, setApiKey] = useState('')

  useEffect(() => {
    if (!opened) {
      setApiKey('')
      setEncodedKey('')

      onClose()
    }
  }, [opened])

  useEffect(() => {
    if (copyedKey && opened) {
      setApiKey(copyedKey)
      setEncodedKey(encode(copyedKey))
    }
  }, [copyedKey, opened])

  return (
    <Card p={24} sx={{ flex: 1 }}>
      <Flex justify="space-between" align="top">
        <Typography variant="title-md" mb={4}>
          {title}
        </Typography>
        <Button
          size="compact-xs"
          h={28}
          variant="default"
          data-mp-event="Data Service config button clicked"
          onClick={open}
        >
          Get Configuration
        </Button>
      </Flex>

      <Flex align="center" gap={18} mt={4}>
        <Box component={IconDataService} c="carbon.6" w={40} h={40}></Box>
        <Box component={IconXClose} c="carbon.6" w={24} h={24}></Box>
        {logo}
      </Flex>

      <Typography variant="body-md" mt={8} sx={{ whiteSpace: 'break-spaces' }}>
        {desc}
      </Typography>

      <Modal zIndex={1} title={title} opened={opened} size={640} centered trapFocus={false} onClose={close}>
        <Typography variant="body-lg">{desc}</Typography>

        <TextInput
          label={
            <Flex align="center" gap={4}>
              <Typography>API Specification URL</Typography>
              <HoverCard width={400} withArrow position="top" shadow="md">
                <HoverCard.Target>
                  <Box component={IconInfoCircle} sx={{ cursor: 'pointer' }} />
                </HoverCard.Target>
                <HoverCard.Dropdown>
                  <Typography variant="body-md">
                    Provides the OpenAPI Specification URL for your Data App. When prompted use this link for GPT
                    integration with your Data Service.
                  </Typography>
                </HoverCard.Dropdown>
              </HoverCard>
            </Flex>
          }
          mt={32}
          readOnly
          rightSection={
            <CopyButton value={editApp?.open_api_link ?? ''} timeout={1000}>
              {({ copied, copy }) => (
                <Tooltip label={copied ? 'Copied' : 'Copy'} withArrow position="top">
                  <Box sx={{ cursor: 'pointer' }}>
                    <IconCopy03 onClick={copy} />
                  </Box>
                </Tooltip>
              )}
            </CopyButton>
          }
          value={editApp?.open_api_link}
        />

        <Flex align="flex-end" gap={24}>
          <TextInput
            label="API Key"
            mt={32}
            sx={{
              flex: 1
            }}
            value={apiKey}
            rightSection={
              <CopyButton value={apiKey ?? ''} timeout={1000}>
                {({ copied, copy }) => (
                  <Tooltip label={copied ? 'Copied' : 'Copy'} withArrow position="top">
                    <Box sx={{ cursor: 'pointer' }}>
                      <IconCopy03 onClick={copy} />
                    </Box>
                  </Tooltip>
                )}
              </CopyButton>
            }
            onChange={(e) => {
              setApiKey(e.target.value)
              setEncodedKey(encode(e.target.value))
            }}
          />
          <Button variant="default" onClick={() => onOpenApiKeyModal()}>
            Create API Key
          </Button>
        </Flex>

        <TextInput
          label={
            <Flex align="center" gap={4}>
              <Typography>API Key Encoded</Typography>
              <HoverCard width={400} withArrow position="top" shadow="md">
                <HoverCard.Target>
                  <Box component={IconInfoCircle} sx={{ cursor: 'pointer' }} />
                </HoverCard.Target>
                <HoverCard.Dropdown>
                  <Typography variant="body-md">
                    API Key Encoded field contains the base64-encoded version of your API key, designed for seamless
                    integration with GPT configuration. Ensure to use this encoded string when configuring GPT settings.
                  </Typography>
                </HoverCard.Dropdown>
              </HoverCard>
            </Flex>
          }
          mt={32}
          value={encodedKey}
          rightSection={
            <CopyButton value={encodedKey} timeout={1000}>
              {({ copied, copy }) => (
                <Tooltip label={copied ? 'Copied' : 'Copy'} withArrow position="top">
                  <Box sx={{ cursor: 'pointer' }}>
                    <IconCopy03 onClick={copy} />
                  </Box>
                </Tooltip>
              )}
            </CopyButton>
          }
          readOnly
        />
      </Modal>
    </Card>
  )
}

export default GptIntegration
