import { Box, Button, Flex, Group, Input, Modal, notifier, Typography } from '@tidbcloud/uikit'
import { DateTimePicker, useDateTimePicker } from '@tidbcloud/uikit/biz'
import dayjs from 'dayjs'
import { observer } from 'mobx-react'
import { useCallback, useEffect, useRef, useState } from 'react'

import TimeComponent from 'dbaas/components/TimeComponent'
import { utcOffsetToTz } from 'dbaas/screens/OrgSettings/features/General/helpers'
import { maintenanceServiceUpdateMaintenanceTask } from 'dbaas/services/api-clients/v2023/dedicated/v1beta1'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'
import { formatTime } from 'dbaas/utils/format'

import { useMaintenanceWindowContext } from './context'

export const DeferModal = observer(() => {
  const {
    store: { tenantData, activeProject: project }
  } = useStores()
  const utcoffset = utcOffsetToTz(tenantData.timezone || 0)
  const userSetTimezone = `UTC${utcoffset === '+00:00' ? '±00:00' : utcoffset}`

  const { deferModalOpened, setDeferModalOpened, taskData, getTaskList } = useMaintenanceWindowContext()

  const [loading, setLoading] = useState<boolean>(false)

  const [scheduledApplyTime, setScheduledApplyTime] = useState('')
  const scheduledApplyTimeRef = useRef('')

  useEffect(() => {
    setScheduledApplyTime(
      !taskData?.scheduledApplyTime || dayjs(taskData?.scheduledApplyTime).isBefore(new Date())
        ? new Date().toISOString()
        : taskData?.scheduledApplyTime
    )
  }, [taskData?.scheduledApplyTime])

  useEffect(() => {
    scheduledApplyTimeRef.current = scheduledApplyTime
  }, [scheduledApplyTime])

  const onSubmit = useCallback(async () => {
    setLoading(true)
    try {
      if (!taskData?.maintenanceTaskId) return
      await maintenanceServiceUpdateMaintenanceTask(
        taskData.maintenanceTaskId,
        {
          scheduledApplyTime: scheduledApplyTimeRef.current
        },
        {
          orgId: tenantData.id,
          projectId: project.id
        }
      )
      setDeferModalOpened(false)
      getTaskList()
    } catch (e) {
      notifier.error(getErrorMessage(e))
    } finally {
      setLoading(false)
    }
  }, [tenantData.id, project.id, taskData?.maintenanceTaskId])

  const dateTimePickerProps = useDateTimePicker({
    startDate: new Date(),
    endDate:
      taskData?.deadline && !dayjs(taskData.deadline).isBefore(new Date())
        ? dayjs(taskData.deadline).toDate()
        : undefined,
    value: dayjs(scheduledApplyTime).toDate(),
    format: 'YYYY-MM-DD HH:mm',
    utcOffset: tenantData.timezone,
    onChange: (val) => setScheduledApplyTime(new Date(dayjs(val).format('YYYY-MM-DD HH:mm Z')).toISOString()),
    formatter: (val) => {
      return formatTime(val, {
        offset: tenantData.timezone,
        showSeconds: false,
        showTimezone: false
      })
    }
  })

  return (
    <Modal
      centered
      title="Reschedule"
      opened={deferModalOpened}
      size={640}
      // TODO: remove after picker support withseconds
      styles={{
        content: {
          transform: 'none !important',
          overflow: 'visible',
          '.mantine-Popover-dropdown': {
            '.mantine-ScrollArea-root': {
              '&:last-child': {
                display: 'none'
              }
            },
            '.mantine-Stack-root': {
              '.mantine-Flex-root:nth-of-type(1)': {
                div: {
                  '&:last-child': {
                    display: 'none'
                  }
                }
              }
            }
          }
        },
        header: {
          position: 'static'
        }
      }}
      onClose={() => setDeferModalOpened(false)}
    >
      <Box
        sx={(t) => ({
          backgroundColor: t.colors.carbon[2],
          padding: 12,
          borderRadius: t.defaultRadius,
          marginBottom: 16
        })}
      >
        <Group align="center">
          <Typography variant="title-md">Description:</Typography>
          <Typography>[ {taskData?.description} ]</Typography>
        </Group>
        <Group align="center" mt={8}>
          <Typography variant="title-md">Start Time:</Typography>
          <TimeComponent time={taskData?.scheduledApplyTime ?? ''} format="YYYY-MM-DD HH:mm:ss Z" />
        </Group>
      </Box>

      <Typography>Reschedule Start Time</Typography>
      <Flex gap={16}>
        <DateTimePicker {...dateTimePickerProps} withinPortal={false} />
        <Input disabled value={userSetTimezone} />
      </Flex>
      <Group justify="flex-end" mt={16}>
        <Button variant="default" onClick={() => setDeferModalOpened(false)} data-mp-event="mp-cancel-1691461014312">
          Cancel
        </Button>
        <Button loading={loading} onClick={onSubmit} data-mp-event="mp-submit-1691461014314">
          Confirm
        </Button>
      </Group>
    </Modal>
  )
})
