import { Flex } from '@tidbcloud/uikit'
import { Table, Button, Input, Form, notification, Space } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import { useState } from 'react'
import { Link } from 'react-router-dom'

import {
  useGetProjectResource,
  useGetOrgProjects
} from 'apiClient/services/account'
import { FormsProject } from 'apiClient/services/account/interface'
import { deleteProject } from 'apiClient/services/devops'
import ModalForm from 'components/ModalForm'
import { getErrorMessage } from 'utils/error'
import { format } from 'utils/time'

import { AddUser } from '../Users/AddUser'

export const DeleteProject: React.FC<
  React.PropsWithChildren<{
    orgId: string
    projectId: string
    projectName: string
  }>
> = ({ orgId, projectId, projectName }) => {
  const [visible, setVisible] = useState(false)

  const { data, isLoading, refetch } = useGetProjectResource(orgId, projectId, {
    query: {
      enabled: false,
      refetchOnMount: false,
      refetchInterval: false,
      cacheTime: 10 * 1000,
      onSuccess: () => {
        setVisible(true)
      },
      onError: (err) => {
        notification.error({ message: getErrorMessage(err) })
      }
    }
  })

  const haveResource = data?.data.is_have_resource

  const onSubmit = async (data: { reason: string }) => {
    if (haveResource) {
      setVisible(false)
      return
    }
    await deleteProject(orgId, projectId, {
      tenant_id: orgId,
      project_id: projectId,
      reason: data.reason
    })
    setVisible(false)
  }

  const onCancel = () => {
    setVisible(false)
  }

  const getFields = () => {
    if (haveResource) {
      return (
        <>
          <p
            dangerouslySetInnerHTML={{ __html: data?.data.resources_msg || '' }}
          />
          <p>Please make sure resources are deleted and then try again</p>
        </>
      )
    }
    return (
      <>
        <p>
          Deleting a project is a sensitive operation, make sure it is approved
          before execution.
        </p>
        <p>
          Once your request is approved, the project will be deleted immediately
        </p>
        <p>
          Delete Project:{' '}
          <b>
            {projectName}(ID: {projectId})
          </b>
        </p>
        <Form.Item
          label="Reason"
          name="reason"
          required
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input.TextArea rows={3} placeholder="Reason to delete the project" />
        </Form.Item>
      </>
    )
  }

  return (
    <>
      <Button type="link" danger onClick={() => refetch()} loading={isLoading}>
        {isLoading ? 'Checking' : 'Delete'}
      </Button>
      <ModalForm
        visible={visible}
        title={
          haveResource ? 'Deleting project is not allowed' : 'Delete project'
        }
        onSubmit={onSubmit}
        onCancel={onCancel}
        getFields={getFields}
        name="delete-project-form"
        okText={haveResource ? 'OK' : ' Send to approve'}
      ></ModalForm>
    </>
  )
}

export const Projects: React.FC<React.PropsWithChildren<{ orgId: string }>> = ({
  orgId
}) => {
  const [currentPage, setCureentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const { data, isLoading, refetch } = useGetOrgProjects(
    orgId,
    {
      page: currentPage,
      page_size: pageSize
    },
    {
      query: {
        refetchInterval: false,
        refetchOnWindowFocus: false
      }
    }
  )

  const onPageChange = (page: number, pageSize: number) => {
    setCureentPage(page)
    setPageSize(pageSize || 10)
  }

  const columns: ColumnsType<FormsProject> = [
    {
      title: 'Project ID',
      dataIndex: 'id'
    },
    {
      title: 'Project Name',
      dataIndex: 'name'
    },
    {
      title: 'Creation Time',
      dataIndex: 'created_at',
      render(value, record) {
        return format((record.created_at?.seconds || 0) * 1000)
      }
    },
    {
      title: 'Clusters',
      dataIndex: 'active_clusters_count'
    },
    {
      title: 'Users',
      dataIndex: 'user_count'
    },
    {
      title: 'CMEK',
      dataIndex: 'aws_cmek_enabled',
      render(value) {
        return value ? 'Enabled' : 'Disabled'
      }
    },
    {
      title: 'Actions',
      width: 300,
      render(value, record, index) {
        return (
          <div key={record.id}>
            <AddUser
              type="project"
              projectName={record.name || ''}
              orgId={orgId}
              projectId={record.id}
              onComplete={refetch}
            />
            <DeleteProject
              orgId={orgId}
              projectId={record.id || ''}
              projectName={record.name || ''}
            />
            <Space>
              <Link to={`/orgs/${orgId}/projects/${record.id}`}>Detail</Link>
            </Space>
          </div>
        )
      }
    }
  ]

  return (
    <>
      <Flex justify="flex-end"></Flex>
      <Table
        columns={columns}
        loading={isLoading}
        dataSource={data?.data.items || []}
        pagination={{
          total: data?.data.total || 10,
          current: currentPage,
          pageSize: pageSize,
          onChange: onPageChange
        }}
      ></Table>
    </>
  )
}
