import { notifier } from '@tidbcloud/uikit'
import { Button, Checkbox, Group, Loader, Modal, Stack, Typography } from '@tidbcloud/uikit'
import { useState, useEffect, useMemo } from 'react'

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

/**
 * Get AI privacy settings
 */
function useFetchAIPrivacySetting(options?: {
  onSuccess?: (enabled: boolean) => void
  onError?: (errMsg: string) => void
}) {
  const { onSuccess, onError } = options || {}

  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId: projectId
    }
  } = useStores()

  const {
    data: response,
    isLoading,
    isSuccess,
    isError,
    refetch
  } = useGetAIUserSetting(orgId, projectId, {
    query: {
      onSuccess: (response) => {
        if (response?.code === 200) {
          onSuccess?.(response.data?.is_privacy_allowed || false)
        }
      }
    }
  })
  const enabled = response?.data?.is_privacy_allowed || false
  const { isFailed, errMsg } = useMemo(() => {
    if (isError || (isSuccess && !response)) {
      return {
        isFailed: true,
        errMsg: 'Get AI privacy settings error'
      }
    } else if (response?.code !== 200 && !!response?.message) {
      return {
        isFailed: true,
        errMsg: response.message
      }
    }

    return {
      isFailed: false,
      errMsg: ''
    }
  }, [isError, isSuccess, response])

  useEffect(() => {
    if (isFailed) {
      onError?.(errMsg)
    }
  }, [errMsg, isFailed, onError])

  return {
    isLoading,
    enabled,
    refetch
  }
}

export const AiPowerPrivacy = ({ styleBold }: { styleBold?: boolean }) => {
  const {
    store: {
      tenantData: { id: orgId },
      activeProjectId: projectId
    }
  } = useStores()

  const [aiModalVisible, setAIModalVisible] = useState(false)
  const [aiEnabled, setAIEnabled] = useState(false)

  const { isLoading: aiPrivacyLoading, refetch: refetchAIPrivacy } = useFetchAIPrivacySetting({
    onSuccess: (enabled) => {
      setAIEnabled(enabled)
    },
    onError: (errMsg) => {
      notifier.error(errMsg)
    }
  })
  const aiPrivacyMutation = useUpdateAIUserSetting({
    mutation: {
      onSuccess: () => {
        refetchAIPrivacy()
        notifier.success('Your privacy information has been successfully saved.')
      },
      onError(_error, variables) {
        setAIEnabled(!variables.data.is_privacy_allowed)
        notifier.error('Fail to save your privacy information. Please try again later.')
      }
    }
  })

  const saveAIPrivacy = (enabled: boolean) => {
    setAIEnabled(enabled)

    return aiPrivacyMutation.mutateAsync({
      orgId,
      projectId,
      data: {
        chat2query_init: true,
        is_privacy_allowed: enabled
        // chat2query_init: false,
        // is_privacy_allowed: false
      }
    })
  }

  const onAIPrivacyCheck = (checked?: boolean) => {
    if (checked) {
      saveAIPrivacy(checked)
    } else {
      setAIModalVisible(true)
    }
  }

  const confirmAIDisabled = async () => {
    await saveAIPrivacy(false)

    setAIModalVisible(false)
  }

  return (
    <>
      <Checkbox
        size="xs"
        styles={() => ({
          label: {
            cursor: 'pointer'
          },
          inner: {
            marginTop: 2
          },
          input: {
            cursor: 'pointer'
          }
        })}
        label={
          <Group gap={8} wrap="nowrap" align="flex-start">
            {(aiPrivacyLoading || aiPrivacyMutation.isLoading) && <Loader size="xs" />}
            <Typography variant={styleBold ? 'label-lg' : 'body-lg'}>
              We use AI to improve your experience. By continuing, you consent to PingCAP's use of AI to process your
              code snippets via our AI-powered functions to improve our Services.
            </Typography>
          </Group>
        }
        disabled={aiPrivacyLoading || aiPrivacyMutation.isLoading}
        checked={aiEnabled}
        onChange={(e) => onAIPrivacyCheck(e.target.checked)}
      />
      <Typography ml={styleBold ? 28 : 0} variant={styleBold ? 'label-lg' : 'body-lg'}>
        Learn more in our{' '}
        <a
          href="https://www.pingcap.com/legal/ai-powered-functions-privacy-statement/"
          target="_blank"
          rel="noreferrer"
        >
          AI-Powered Functions Privacy Statement
        </a>
        .
      </Typography>
      <Modal
        size={700}
        centered
        withCloseButton={false}
        opened={aiModalVisible}
        onClose={() => setAIModalVisible(false)}
        title="AI-powered Data Exploration"
      >
        <Typography variant="body-lg" mb={16}>
          AI-powered data exploration will 10-times accelerate your journey of data insights. Are you sure you want to
          disable it?
        </Typography>
        <Group gap="md" justify="flex-end">
          <Button variant="default" onClick={() => setAIModalVisible(false)} data-mp-event="mp-cancel-1691461013117">
            Cancel
          </Button>
          <Button
            loading={aiPrivacyMutation.isLoading}
            onClick={confirmAIDisabled}
            data-mp-event="mp-continue-1691461013119"
          >
            Continue
          </Button>
        </Group>
      </Modal>
    </>
  )
}

export const AIPrivacy = () => {
  return (
    <>
      <Stack gap={8} mb={32}>
        <Typography variant="title-lg">TiDB Cloud</Typography>
        <Typography variant="body-lg">
          More information in{' '}
          <a href="https://www.pingcap.com/privacy-policy/" target="_blank" rel="noreferrer">
            PingCAP Privacy Policy
          </a>
          .
        </Typography>
      </Stack>

      <Stack gap={8}>
        <Typography variant="title-lg">AI-powered Data Exploration</Typography>
        <AiPowerPrivacy />
      </Stack>
    </>
  )
}

export default AIPrivacy
