import { ActionIcon, HoverCard, Loader, Typography } from '@tidbcloud/uikit'
import { IconDownload01 } from '@tidbcloud/uikit/icons'
import { useState } from 'react'

import { getChat2Querylogs } from 'dbaas/services/dataservice'

import { downFile } from '../../utils'

type LogParams = {
  start: number
  end: number
  status: string
  type: string
  question: string
}

interface LogProps extends LogParams {
  orgId: string
  projectId: string
  appId: string
}

const LogActions = ({ orgId, projectId, appId, ...reset }: LogProps) => {
  const [isLoading, setIsLoading] = useState(false)

  const downFileSuffix = () => {
    const date = new Date()
    const year = date.getFullYear()
    const month = `${date.getMonth() + 1}`.padStart(2, '0')
    const day = `${date.getDate()}`.padStart(2, '0')
    const hour = `${date.getHours()}`.padStart(2, '0')
    const min = `${date.getMinutes()}`.padStart(2, '0')
    const sec = `${date.getSeconds()}`.padStart(2, '0')
    return `${year}${month}${day}${hour}${min}${sec}`
  }

  const downloadLogs = async () => {
    setIsLoading(true)
    try {
      const list = await getChat2Querylogs(
        orgId,
        projectId,
        appId,
        {
          start: reset.start,
          end: reset.end,
          status: reset.status,
          type: reset.type,
          question: reset.question,
          download: true
        },
        {
          responseType: 'arraybuffer'
        }
      )

      await downFile(list as ArrayBuffer, `tcds_chat2query_logs_${downFileSuffix()}.json`)
    } catch (_e) {
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <HoverCard width={350} shadow="md">
      <HoverCard.Target>
        <ActionIcon aria-label="Download logs" variant="subtle" color="gray" onClick={downloadLogs}>
          {isLoading ? <Loader size={16} /> : <IconDownload01 size={16} />}
        </ActionIcon>
      </HoverCard.Target>
      <HoverCard.Dropdown>
        <Typography variant="body-lg">
          Download log files, arranged from most recent to oldest, for up to a maximum of 30 days with a limit of 10,000
          logs.
        </Typography>
      </HoverCard.Dropdown>
    </HoverCard>
  )
}

export default LogActions
