import { Button, Form, Input } from 'antd'
import { useState } from 'react'

import {
  removeUserFromTenant,
  removeUserFromProject
} from 'apiClient/services/devops'
import ModalForm from 'components/ModalForm'

interface DeleteUserProps {
  type: 'org' | 'project'
  orgId: string
  userId: string
  projectId?: string
  email: string
  orgName?: string
  projectName?: string
  onComplete?: () => void
}

export const DeleteUser: React.FC<React.PropsWithChildren<DeleteUserProps>> = ({
  orgId,
  type,
  userId,
  projectId,
  email,
  onComplete,
  orgName,
  projectName
}) => {
  const [visible, setVisible] = useState(false)
  const onSubmit = async (data: { reason: string }) => {
    if (type === 'project') {
      await removeUserFromProject(orgId, projectId || '', userId, {
        tenant_id: orgId,
        project_id: projectId || '',
        user_id: userId,
        user_email: email,
        reason: data.reason
      })
    } else {
      await removeUserFromTenant(orgId, userId, {
        tenant_id: orgId,
        user_id: userId,
        user_email: email,
        reason: data.reason
      })
    }
    setVisible(false)
    onComplete?.()
  }

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

  const getFields = () => {
    return (
      <>
        <p>
          Are you sure to delete this user: <b>{email}</b>, from org: {orgName}
          (ID: {orgId}){' '}
          {type === 'project' && (
            <>
              , project: {projectName}(ID: {projectId})
            </>
          )}
          ?
        </p>
        <Form.Item
          label="Reason"
          name="reason"
          required
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input.TextArea rows={3} placeholder="Reason to delete the user" />
        </Form.Item>
      </>
    )
  }

  return (
    <>
      <Button
        danger
        type="link"
        onClick={() => setVisible(true)}
        style={{ paddingLeft: 0, paddingRight: 0 }}
      >
        Delete
      </Button>
      <ModalForm
        visible={visible}
        title={
          type === 'project'
            ? 'Delete user from project'
            : 'Delete user from org'
        }
        onSubmit={onSubmit}
        onCancel={onCancel}
        getFields={getFields}
        okText="Confirm"
        name="delete-user-form"
      ></ModalForm>
    </>
  )
}
