import { ActionIcon, Box, Flex, Typography } from '@tidbcloud/uikit'
import { IconRefreshCw02 } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'

import TimeComponent from 'dbaas/components/TimeComponent'
import { useGetDataappDeployList } from 'dbaas/services/dataservice'

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

import DeployList from './List'

const Deployment = () => {
  const { orgId, projectId, editApp } = useDataApiContext()
  const COUNT = 25 // front-end max num is 25
  const [isFetchManual, setIsFetchManual] = useState(false)

  useEffect(() => {
    refetch()
  }, [])

  const { data, isFetching, refetch } = useGetDataappDeployList(
    orgId,
    projectId,
    `${editApp?.id}`,
    {
      limit: `${COUNT}`
    },
    {
      query: {
        enabled: !!orgId && !!projectId && !!editApp?.id,
        refetchInterval: 5 * 1000,
        refetchOnWindowFocus: false
      }
    }
  )

  useEffect(() => {
    if (!isFetching) {
      setIsFetchManual(false)
    }
  }, [isFetching])

  return (
    <Box
      sx={{
        height: '100%',
        overflowY: 'auto',
        marginLeft: -16,
        marginRight: -16
      }}
    >
      <Flex px={16} sx={{ flexWrap: 'nowrap' }} justify="space-between" mt={16}>
        <Flex align="center">
          <Typography variant="body-lg" c="carbon.7">
            last deployment at: <TimeComponent time={data?.data?.[0]?.created_at ?? ''} />
          </Typography>
          <ActionIcon
            aria-label="Refresh"
            variant="subtle"
            ml={16}
            loading={isFetchManual}
            data-mp-event="Dataservice deployment list refresh button clicked"
            onClick={() => {
              setIsFetchManual(true)
              refetch()
            }}
          >
            <IconRefreshCw02 size={16} />
          </ActionIcon>
        </Flex>
        <Typography variant="body-lg" c="carbon.7">
          Shows Last 25 Deployments
        </Typography>
      </Flex>
      <DeployList data={data?.data || []} loading={isFetchManual} fetch={refetch} />
    </Box>
  )
}

export default Deployment
