import { Alert, Box, Button, Flex, Modal, Typography } from '@tidbcloud/uikit'
import { useEffect, useState } from 'react'

import { useDataApiContext } from '../context'
import { useTestEndpoint } from '../helpers'
import { EndPoint } from '../types'

import EndpointDraftDiff from './EndpointDraftDiff'

const EndpointConflictBar = () => {
  const { getEndPointDetail, conflictEndpointId, setConflictEndpointId, editEndpoint, setIsAutoSaveClose } =
    useDataApiContext()
  const { saveEndpoint } = useTestEndpoint()
  const [isSaving, setIsSaving] = useState(false)
  const [opened, setOpened] = useState(false)

  useEffect(() => {
    setIsAutoSaveClose(opened)
  }, [opened])

  const keepDraft = async () => {
    setIsSaving(true)
    await saveEndpoint({
      vid: '0' // force
    })
    setIsSaving(false)
    setOpened(false)
  }

  const updateDraft = async () => {
    setConflictEndpointId('')
    getEndPointDetail(editEndpoint as EndPoint, true)
    setOpened(false)
  }

  if (!conflictEndpointId || conflictEndpointId !== `${editEndpoint?.id}`) {
    return null
  }

  return (
    <Box>
      <Alert
        m="8px 12px 4px"
        color="yellow"
        styles={() => ({
          root: {
            padding: '8px 8px 8px 16px'
          }
        })}
      >
        <Flex justify="space-between" align="center">
          <Typography variant="body-lg" c="yellow.9">
            The endpoint you are currently accessing is being edited elsewhere.
          </Typography>
          <Button
            size="xs"
            variant="outline"
            color="yellow.7"
            data-mp-event="Dataservice endpoint conflict message bar button clicked"
            onClick={() => setOpened(true)}
          >
            Review Diff
          </Button>
        </Flex>
      </Alert>

      <Modal title="Review Diff" size="80%" opened={opened} centered trapFocus={false} onClose={() => setOpened(false)}>
        <EndpointDraftDiff />
        <Flex align="center" justify="space-between" mt={16}>
          <Flex gap={16}>
            <Typography c="red.8">【 - 】 Deleted from local files</Typography>
            <Typography c="green.8">【 + 】 Added elsewhere</Typography>
          </Flex>
          <Box>
            <Button
              variant="light"
              color="sky"
              loading={isSaving}
              mr={16}
              onClick={keepDraft}
              data-mp-event="mp-keep&savelocal-1691461014582"
            >
              Ignore changes & Keep local version
            </Button>
            <Button onClick={updateDraft} data-mp-event="mp-update-1691461014584">
              Apply changes and overwrite local version
            </Button>
          </Box>
        </Flex>
      </Modal>
    </Box>
  )
}

export default EndpointConflictBar
