import { Anchor, ActionIcon, Card, CardProps, Modal, Typography, Flex, Loader } from '@tidbcloud/uikit'
import { IconPlus, IconDataAppAi } from '@tidbcloud/uikit/icons'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'

import { useGetDataApps } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'

interface AppBtnProps extends CardProps {
  title: string
  descriptions?: React.ReactNode[]
  active?: boolean
  icon?: React.ReactNode
  onClick?: () => void
  onMouseDown?: () => void
}

const HoverCard: React.FC<React.PropsWithChildren<AppBtnProps>> = ({
  title,
  descriptions,
  active,
  icon,
  onClick,
  onMouseDown,
  ...restProps
}) => {
  const handleClick = () => {
    onClick?.()
  }

  return (
    <Card
      {...restProps}
      withBorder
      p="md"
      sx={(theme) => {
        const diffStyles = {
          normal: {
            static: {},
            hover: {
              cursor: 'pointer',
              borderColor: theme.colors.carbon[5],
              boxShadow: '0px 4px 16px rgba(0, 0, 0, 0.05)'
            },
            active: {
              borderColor: theme.colors.peacock[4]
            }
          },
          active: {
            static: {
              borderColor: theme.colors.peacock[5]
            },
            hover: {
              cursor: 'pointer'
            }
          }
        }
        const styles = diffStyles[active ? 'active' : 'normal']

        return {
          ...styles.static,
          '&:hover': styles.hover
        }
      }}
      onClick={handleClick}
      onMouseDown={onMouseDown}
    >
      <Flex align="center" gap={8}>
        {icon && <ActionIcon variant="transparent">{icon}</ActionIcon>}
        <Typography variant="label-lg" c="carbon.8">
          {title}
        </Typography>
      </Flex>
    </Card>
  )
}

const Chat2DataModal = ({ onClose }: { onClose: () => void }) => {
  const [opened, setOpened] = useState(true)
  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId: projectId
    }
  } = useStores()
  const history = useHistory()

  const [activeAppIndex, setActiveAppIndex] = useState(-1)
  const { data, isLoading } = useGetDataApps(orgId, projectId, undefined, {
    query: {
      enabled: !!orgId && !!projectId && opened,
      refetchOnWindowFocus: false
    }
  })

  return (
    <Modal
      size={480}
      title="Access Chat2Query via API"
      opened={opened}
      trapFocus={false}
      centered
      onClose={() => {
        setOpened(false)
        onClose()
      }}
    >
      <Typography variant="body-lg">
        Chat2Query Data App is a collection of Chat2Query API endpoints. Find more details about{' '}
        <Anchor href="https://docs.pingcap.com/tidbcloud/use-chat2query-api" target="_blank" ml={4}>
          Chat2Query API endpoints
        </Anchor>
        .
      </Typography>
      <Typography variant="body-lg" mt={8} mb={16}>
        You can access Chat2Query API either from an existing Chat2Query Data App or create a new Chat2Query Data App.{' '}
      </Typography>

      <HoverCard
        icon={<IconPlus size={24} />}
        title="New Chat2Query Data App"
        active={activeAppIndex === 0}
        onClick={() => {
          setActiveAppIndex(0)
          history.push({ pathname: '/project/data-service', search: '?type=chat2data' })
        }}
      />

      {isLoading && <Loader size="sm" m={16} />}

      {(data?.data || [])
        .filter((app) => app.app_type === 'chat2query')
        .map((app, index) => (
          <HoverCard
            icon={<IconDataAppAi size={24} />}
            title={app.app_name ?? ''}
            my={16}
            active={index === activeAppIndex - 1}
            onMouseDown={() => setActiveAppIndex(index + 1)}
            onClick={() => {
              setActiveAppIndex(index + 1)
              delete app.endpoints
              localStorage.setItem('data-service-edit-app', JSON.stringify(app))
              history.push({ pathname: '/project/data-service' })
            }}
          />
        ))}
    </Modal>
  )
}

export default Chat2DataModal
