import React from 'react'

import { hideNotification, showNotification } from '@mantine/notifications'
import { ActionIcon, Card, Group, Title } from '@tidbcloud/uikit'
import { IconArrowCircleLeft } from '@tidbcloud/uikit/icons'
import { useNavigate, useParams } from 'react-router-dom'

import { useCurCluster, useCurOrg } from '~/hooks/state'
import { useMutation } from '~/hooks/use-mutation'

import { createStrategy } from '../api'
import type { HealthcheckHealthCheckStrategyReq } from '../types'
import { StrategyForm } from './StrategyForm'

const CreateStrategyPage: React.FC = () => {
  const navigate = useNavigate()
  const { orgId, cid } = useParams<'orgId' | 'cid'>()

  const { curOrg } = useCurOrg()
  const { curCluster } = useCurCluster()

  const oid = curOrg!.id!
  const clusterId = curCluster!.id!

  const { loading: creating, run: runCreate } = useMutation(
    (req: HealthcheckHealthCheckStrategyReq) =>
      createStrategy(oid, clusterId, req)
  )

  const goBack = () => {
    navigate(`/orgs/${orgId}/clusters/${cid}/health-check/strategies`)
  }

  const handleSubmit = (strategy: HealthcheckHealthCheckStrategyReq) => {
    runCreate(strategy, (res) => {
      const createdUuid = res?.data?.uuid
      const notifId = 'strategy-created'
      showNotification({
        id: notifId,
        color: 'green',
        autoClose: 8000,
        styles: {
          root: {
            width: 'max-content',
            maxWidth: 'calc(100vw - 32px)',
            overflow: 'visible'
          },
          body: {
            flex: '0 1 auto',
            overflow: 'visible'
          },
          description: {
            overflow: 'visible',
            textOverflow: 'clip',
            whiteSpace: 'nowrap'
          }
        },
        message: (
          <div
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 8,
              maxWidth: 'none',
              whiteSpace: 'nowrap'
            }}
          >
            <span style={{ flex: '0 0 auto' }}>
              Strategy &quot;{strategy.name}&quot; created successfully.
            </span>
            {createdUuid && (
              <button
                style={{
                  background: 'none',
                  border: 'none',
                  color: 'var(--mantine-color-blue-6)',
                  cursor: 'pointer',
                  textDecoration: 'underline',
                  padding: 0,
                  fontSize: 14,
                  flex: '0 0 auto',
                  whiteSpace: 'nowrap'
                }}
                onClick={() => {
                  hideNotification(notifId)
                  navigate(
                    `/orgs/${orgId}/clusters/${cid}/health-check?strategyUuid=${createdUuid}`
                  )
                }}
              >
                Run Now
              </button>
            )}
          </div>
        )
      })
      goBack()
    })
  }

  return (
    <div>
      <Group gap='xs' mb='lg' align='center'>
        <ActionIcon
          variant='subtle'
          aria-label='back'
          onClick={goBack}
          title='Back to Strategy Management'
        >
          <IconArrowCircleLeft size={20} />
        </ActionIcon>
        <Title order={3}>Create Strategy</Title>
      </Group>

      <Card withBorder p='lg' maw={1080}>
        <StrategyForm
          provider={curCluster?.provider}
          submitLabel='Create'
          submitting={creating}
          onCancel={goBack}
          onSubmit={handleSubmit}
        />
      </Card>
    </div>
  )
}

export default CreateStrategyPage
