import { notifier } from '@tidbcloud/uikit'
import { ActionIcon, Anchor, Box, Flex, Typography, Drawer, Button, Group, Badge } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconXClose, IconCheck, IconEdit03, IconLinkExternal01 } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

import TimeComponent from 'dbaas/components/TimeComponent'
import { useUpdateDeployLogName } from 'dbaas/services/dataservice'
import { EntityDataAppDeploymentLog } from 'dbaas/services/dataservice/interface'

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

import Diff from './Diff'

export const Item = ({ label, content }: { label: string | React.ReactNode; content: string | React.ReactNode }) => {
  return (
    <Flex mb={16} align="center">
      <Typography variant="label-lg" w={100}>
        {label}
      </Typography>
      <Typography sx={{ flex: 1 }} variant="body-lg">
        {content}
      </Typography>
    </Flex>
  )
}

const DeploymentDetail = ({
  opened,
  data,
  close,
  onRename,
  onRedeploy
}: {
  opened: boolean
  data: EntityDataAppDeploymentLog | undefined
  close: () => void
  onRename: (name: string) => void
  onRedeploy: () => void
}) => {
  const { orgId, projectId, editApp } = useDataApiContext()
  const [isEdit, setIsEdit] = useState(false)
  const updateNameMutation = useUpdateDeployLogName()
  const formProps = useForm<{ deploy_name: string }>()
  const { setValue } = formProps

  const updateDeployName = async (values: { deploy_name: string }) => {
    try {
      const name = values.deploy_name || data?.name || ''
      const res = await updateNameMutation.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id}`,
        logId: `${data?.id}`,
        data: {
          deploy_name: name
        }
      })

      if (res.code !== 200) {
        notifier.error(res.message)
      } else {
        setIsEdit(false)
        onRename(name)
      }
    } catch (_e) {}
  }

  useEffect(() => {
    if (isEdit) {
      setValue('deploy_name', data?.name || '')
    }
  }, [isEdit])

  const cancel = () => {
    close()
    setIsEdit(false)
  }

  return (
    <Drawer
      title={<Typography variant="title-lg">Change Detail</Typography>}
      position="right"
      size={640}
      opened={opened}
      trapFocus={false}
      onClose={cancel}
      styles={(theme) => ({
        body: {
          height: 'calc(100% - 70px)'
        },
        header: {
          padding: '12px 24px',
          borderBottom: `1px solid ${theme.colors.carbon[3]}`
        }
      })}
    >
      <Flex direction="column" h="100%">
        <Box p="8px 24px 0" sx={{ flex: 1 }}>
          {isEdit ? (
            <Form withActions={false} form={formProps} onSubmit={updateDeployName}>
              <Item
                label="Changes"
                content={
                  <Flex align="center" gap={0}>
                    <FormTextInput
                      placeholder="Input"
                      styles={() => ({
                        input: {
                          height: 28,
                          minHeight: 28
                        }
                      })}
                      sx={{ flex: 1 }}
                      name="deploy_name"
                    />
                    <ActionIcon
                      aria-label="Cancel"
                      size="sm"
                      ml={8}
                      variant="transparent"
                      data-mp-event="Dataservice change name icon clicked"
                      onClick={() => setIsEdit(false)}
                    >
                      <IconXClose size={14} />
                    </ActionIcon>
                    <ActionIcon aria-label="Save" size="sm" variant="transparent" type="submit" c="blue">
                      <IconCheck size={14} />
                    </ActionIcon>
                  </Flex>
                }
              />
            </Form>
          ) : (
            <Item
              label="Changes"
              content={
                <Flex align="center">
                  <Typography variant="body-md" component="span" sx={{ wordBreak: 'break-all' }}>
                    {data?.name}
                  </Typography>
                  <ActionIcon aria-label="Edit" variant="transparent" ml={4} c="blue" onClick={() => setIsEdit(true)}>
                    <IconEdit03 size={14} />
                  </ActionIcon>
                </Flex>
              }
            />
          )}

          <Item
            label="Status"
            content={
              <Flex align="center">
                <Badge
                  variant="dot"
                  color={data?.status === 'failed' ? 'red' : 'green'}
                  sx={{ position: 'relative', left: -6 }}
                >
                  {data?.status}
                </Badge>
              </Flex>
            }
          />
          {data?.status === 'failed' && <Item label="Error" content={data.status_error_msg} />}

          <Item label="Time" content={<TimeComponent time={data?.deployed_at || ''} />} />
          <Item
            label="Origin"
            content={
              data?.origin === 'UI' ? (
                'TiDB Cloud UI'
              ) : (
                <>
                  {!data?.commit_id ? (
                    '-'
                  ) : (
                    <Anchor target="_blank" href={data?.diff_url}>
                      <Flex align="center">
                        GitHub: {data?.commit_id.slice(0, 7)}
                        <ActionIcon aria-hidden c="peacock.7">
                          <IconLinkExternal01 size={16} />
                        </ActionIcon>
                      </Flex>
                    </Anchor>
                  )}
                </>
              )
            }
          />
          <Diff type="detail" logId={`${data?.id}`} />
        </Box>
        <Group
          justify="right"
          p="16px 24px"
          sx={(theme) => ({
            borderTop: `1px solid ${theme.colors.carbon[3]}`
          })}
        >
          <Button
            variant="default"
            onClick={() => {
              cancel()
              onRedeploy()
            }}
            data-mp-event="mp-re-deploy-1691461016851"
          >
            Re-Deploy
          </Button>
        </Group>
      </Flex>
    </Drawer>
  )
}

export default DeploymentDetail
