import { Typography, Box, Alert, Divider, closeModal, openModal } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { FormCheckbox, FormTextInput, Form } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'

import { RBACRoleUINames } from 'dbaas/contexts/access-control'
import { ENTERPRISE_SIGNIN_URL } from 'dbaas/features/Organization'
import { useListUsers } from 'dbaas/services/account'
import { listOrgActiveAuthMethods } from 'dbaas/services/account'
import { CentralUser } from 'dbaas/services/account/interface'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

export interface EnableSSOProps {
  onSubmit: (data: SSOFormData) => Promise<void>
  orgId: string
}

const UsersTable = observer(() => {
  const {
    store: { tenantData, userProfile }
  } = useStores()
  const { data } = useListUsers(tenantData.id, { page: 1, per_page: 1000 })
  const columns: MRT_ColumnDef<CentralUser>[] = [
    {
      header: 'User',
      accessorKey: 'email',
      size: 432
    },
    {
      header: 'Role',
      accessorFn: ({ rbac_role: role }) => {
        return RBACRoleUINames[role]
      }
    }
  ]
  const users = data?.items.filter((user) => user.email.toLowerCase() !== userProfile.email.toLowerCase()) || []
  if (!users.length) {
    return null
  }
  return (
    <div>
      <Alert icon={<IconAlertCircle size={14} />} color="yellow">
        <Typography variant="body-lg" c="yellow.9">
          The following users will receive an email notification to re-join the organization once Cloud Organization SSO
          is enabled.
        </Typography>
      </Alert>
      <ProTable
        columns={columns}
        data={users}
        enableStickyHeader
        emptyMessage="No Data"
        mantinePaperProps={{ mt: 16 }}
        mantineTableContainerProps={{ sx: { maxHeight: '200px', overflow: 'auto' } }}
      />
    </div>
  )
})

interface SSOFormData {
  company_name: string
  checked: boolean
}

const SSOAlerts = () => {
  const { watch } = useFormContext<SSOFormData>()
  const company = watch('company_name', '') || 'your-company-name'

  return (
    <div>
      <Alert icon={<IconAlertCircle size={14} />} color="yellow">
        <Typography variant="body-lg" c="yellow.9">
          The URL cannot be changed once Cloud Organization SSO is enabled. Members in your organization will only be
          able to login using the active methods at{' '}
          <b>
            {ENTERPRISE_SIGNIN_URL}/{company}.
          </b>{' '}
          This is not revertable.
        </Typography>
      </Alert>
    </div>
  )
}

export const useEnableSSO = () => {
  const modalId = 'enable-sso-modal'

  const onCancel = () => {
    eventTracking('Cloud Organization SSO Modal Closed')
    closeModal(modalId)
  }

  return {
    open: ({ onSubmit }: EnableSSOProps) => {
      eventTracking('Cloud Organization SSO Modal Opened')
      openModal({
        modalId,
        centered: true,
        trapFocus: false,
        size: 700,
        sx: (theme) => {
          return {
            borderColor: `1px solid ${theme.colors.carbon[4]}`
          }
        },
        styles: {
          body: {
            paddingTop: 0
          }
        },
        title: (
          <Box>
            <Typography variant="title-lg">Enable Cloud Organization SSO</Typography>
          </Box>
        ),
        children: (
          <div>
            <Divider mx={-24} mb={16}></Divider>
            <Typography variant="body-lg" mb={16}>
              Please confirm that you want to enable Cloud Organization SSO.
            </Typography>
            <Form<SSOFormData>
              defaultValues={{ company_name: '', checked: false }}
              onSubmit={async (data: SSOFormData) => {
                await onSubmit(data)
                closeModal(modalId)
              }}
              onCancel={onCancel}
              actionsProps={{ confirmText: 'Enable' }}
            >
              <FormTextInput
                leftLabel={ENTERPRISE_SIGNIN_URL + '/'}
                name="company_name"
                label="Custom URL"
                rules={{
                  required: 'Required',
                  pattern: {
                    value: /^[A-Za-z0-9_-]{1,128}$/,
                    message:
                      'Company name must be 1~128 characters that can only include numbers, lowercase or uppercase letters, underscore and hyphens.'
                  },
                  validate: async (value) => {
                    try {
                      const data = await listOrgActiveAuthMethods({ company_name: value })
                      if (data.auth_methods?.length) {
                        return 'Company name is used.'
                      }
                      return true
                    } catch (_e) {
                      return true
                    }
                  }
                }}
              />
              <SSOAlerts />
              <UsersTable />
              <FormCheckbox name="checked" rules={{ required: 'Please confirm' }} label="I understand and confirm." />
            </Form>
          </div>
        )
      })
    }
  }
}
