import { Anchor, Stack } from '@tidbcloud/uikit'
import { useState } from 'react'
import { useQueryClient } from 'react-query'

import { DtoShowUserInfoRes, useGetAIUserSetting, useUpdateAIUserSetting } from 'dbaas/services'
import useStores from 'dbaas/stores/useStores'

import { ActionMessage, TipsMessage, UserMessage } from './Messages'

export const PrivacyMessages: React.FC<React.PropsWithChildren<{ onPrivacyChange: (allowed: boolean) => void }>> = ({
  onPrivacyChange
}) => {
  const { isPrivacyAllowed, isPrivacyLoading, isPrivacyUpdating, updateAIPrivacy } = useAIPrivacy()
  const [privacyChanged, setPrivacyChanged] = useState(false)
  const changePrivacy = async (allowed: boolean) => {
    if (allowed) {
      await updateAIPrivacy(allowed)
    }
    setPrivacyChanged(true)
    onPrivacyChange(allowed)
  }

  const ChangePrivacyActions = () => (
    <Stack gap="xs">
      <ActionMessage onClick={() => !isPrivacyUpdating && !isPrivacyLoading && changePrivacy(true)}>
        Yes, I accept.
      </ActionMessage>
      <ActionMessage onClick={() => !isPrivacyUpdating && !isPrivacyLoading && changePrivacy(false)}>
        No, I don't accept.
      </ActionMessage>
    </Stack>
  )

  const PrivacyTips = () =>
    isPrivacyAllowed ? (
      <UserMessage
        msg={{
          displayed: { role: 'user', content: `I accept the AI-Powered Functions Privacy Statement to use TiDB Bot.` }
        }}
      />
    ) : (
      <>
        <UserMessage
          msg={{
            displayed: {
              role: 'user',
              content: `I don't accept the AI-Powered Functions Privacy statement to use TiDB Bot.`
            }
          }}
        />
        <TipsMessage>Sure, you can reopen TiDB Bot to accept it again.</TipsMessage>
      </>
    )

  return (
    <>
      <TipsMessage>
        Welcome to TiDB Bot. Please accept the{' '}
        <Anchor
          href="https://www.pingcap.com/legal/ai-powered-functions-privacy-statement/"
          target="_blank"
          rel="noreferrer"
        >
          AI-Powered Functions Privacy Statement
        </Anchor>{' '}
        to continue using TiDB Bot.
      </TipsMessage>
      {privacyChanged || isPrivacyAllowed ? <PrivacyTips /> : <ChangePrivacyActions />}
    </>
  )
}

export const useAIPrivacy = () => {
  const queryClient = useQueryClient()
  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId: projectId
    }
  } = useStores()
  const { data: response, isLoading, refetch, queryKey } = useGetAIUserSetting(orgId, projectId)
  const allowed = isLoading || !!response?.data?.is_privacy_allowed
  const { isLoading: isUpdating, mutateAsync } = useUpdateAIUserSetting({
    mutation: {
      onMutate: ({ data: { is_privacy_allowed } }) => {
        if (!is_privacy_allowed) {
          return
        }
        queryClient.setQueryData<DtoShowUserInfoRes>(queryKey, (d) => ({
          ...d,
          data: { ...(d?.data || {}), is_privacy_allowed }
        }))
      },
      onSuccess: () => {
        refetch()
      }
    }
  })
  const updateAIPrivacy = (allowed: boolean) => {
    mutateAsync({
      orgId,
      projectId,
      data: {
        is_privacy_allowed: allowed
      }
    })
  }

  return { isPrivacyAllowed: allowed, isPrivacyLoading: isLoading, isPrivacyUpdating: isUpdating, updateAIPrivacy }
}
