import {
  Group,
  SegmentedControl,
  Select,
  TextInput,
  Box
} from '@tidbcloud/uikit'
import { useDebouncedValue } from '@tidbcloud/uikit/hooks'
import { IconXClose, IconSearchSm } from '@tidbcloud/uikit/icons'
import { Switch, Table } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import dayjs from 'dayjs'
import React, { useState } from 'react'

import { useGetOrgProjects } from 'apiClient/services/account'

import { useGetTenantUsers } from '../../../../apiClient/services/devops'
import { AccountcliUser } from '../../../../apiClient/services/devops/interface'

import { RBACRoleUINames, ScopeTypeConst, RBACRolesValues } from './contants'
import { DeleteUser } from './DeleteUser'
import { ProjectUsers } from './ProjectUsers'

export const TenantUsers: React.FC<
  React.PropsWithChildren<{ orgId: string; orgName: string }>
> = ({ orgId, orgName }) => {
  const { data: projectData } = useGetOrgProjects(
    orgId,
    {
      page: 1,
      page_size: 1000
    },
    {
      query: {
        refetchInterval: false,
        refetchOnWindowFocus: false
      }
    }
  )

  const projects = projectData?.data.items || []

  const [invitedProject, setInvitedProject] = useState(projects[0]?.id || '')

  const invitedProjectName =
    (projects || []).find((p) => p.id === invitedProject)?.name || ''

  const [currentPage, setCurrentPage] = useState(1)
  const pageSize = 10
  const [search, setSearch] = useState('')

  const [debouncedSearch] = useDebouncedValue(search, 500)
  const [segmentType, setSegmentType] = useState<string>(ScopeTypeConst.Org)
  const [showFullEmail, setShowFullEmail] = useState<boolean>(false)

  const onSegmentTypeChange = (type: string) => {
    setSegmentType(type)
    setSearch('')
    setCurrentPage(1)
    setShowFullEmail(false)

    if (type === ScopeTypeConst.Project) {
      setInvitedProject(projects[0]?.id || '')
    }
  }

  const onProjectChange = (value: string) => {
    setInvitedProject(value)
    setSearch('')
    setCurrentPage(1)
    setShowFullEmail(false)
  }

  const { data, isLoading, refetch } = useGetTenantUsers(
    orgId,
    {
      search: debouncedSearch,
      page: currentPage,
      page_size: pageSize,
      full_email: showFullEmail
    },
    {
      query: {
        enabled: segmentType === ScopeTypeConst.Org
      }
    }
  )

  const columns: ColumnsType<AccountcliUser> = [
    {
      title: 'User',
      render(value, record, index) {
        return `${record.first_name} ${record.last_name}`
      }
    },
    {
      title: 'Email',
      dataIndex: 'email'
    },
    {
      title: 'Role',
      dataIndex: 'role',
      render(value: RBACRolesValues) {
        return RBACRoleUINames[value]
      }
    },
    {
      title: 'Invite Time',
      render(value, record) {
        return dayjs((record.invite_time?.seconds || 0) * 1000).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      }
    },
    {
      title: 'Status',
      dataIndex: 'status'
    },
    {
      title: 'Last login Time',
      render(value, record) {
        if (!record.login_time) {
          return record.status === 'ACTIVE' ? '-' : 'Has not logged in yet'
        }
        return dayjs((record.login_time?.seconds || 0) * 1000).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      }
    },
    {
      title: 'Actions',
      render(value, record, index) {
        return (
          <DeleteUser
            type="org"
            orgName={orgName}
            orgId={orgId}
            email={record.email || ''}
            userId={record.id || ''}
            onComplete={refetch}
          />
        )
      }
    }
  ]

  const onPaginationChange = (page: number, pageSize?: number) => {
    setCurrentPage(page)
    setSearch('')
  }

  const onSwitchChange = (isChecked: boolean) => {
    setShowFullEmail(isChecked)
    refetch()
  }

  return (
    <>
      <Group mb={24}>
        <SegmentedControl
          value={segmentType}
          onChange={onSegmentTypeChange}
          data={[
            { label: 'By Organization', value: ScopeTypeConst.Org },
            { label: 'By Project', value: ScopeTypeConst.Project }
          ]}
          py={5}
        />
        {segmentType === ScopeTypeConst.Project && !!projects.length && (
          <Select
            data={projects.map(({ id, name }) => ({
              value: id || '',
              label: name || ''
            }))}
            value={invitedProject}
            onChange={onProjectChange}
          />
        )}
        <TextInput
          placeholder="Search by Email"
          value={search}
          rightSection={
            !!search ? (
              <Box
                component={IconXClose}
                size={14}
                sx={{ cursor: 'pointer' }}
                onClick={() => {
                  setSearch('')
                  setCurrentPage(1)
                }}
              ></Box>
            ) : (
              <Box
                component={IconSearchSm}
                size={14}
                sx={{ cursor: 'pointer' }}
              ></Box>
            )
          }
          onChange={(event) => {
            setCurrentPage(1)
            setSearch(event.currentTarget.value)
          }}
        />
        View Email
        <Switch
          checkedChildren="on"
          unCheckedChildren="off"
          defaultChecked={showFullEmail}
          onChange={onSwitchChange}
          checked={showFullEmail}
        />
      </Group>
      {segmentType === ScopeTypeConst.Project ? (
        <ProjectUsers
          orgId={orgId}
          orgName={orgName}
          projectId={invitedProject}
          projectName={invitedProjectName}
          currentPage={currentPage}
          onPageChange={onPaginationChange}
          search={debouncedSearch}
          showFullEmail={showFullEmail}
        />
      ) : (
        <Table
          columns={columns}
          loading={isLoading}
          dataSource={data?.data.items || []}
          pagination={{
            total: data?.data.total || 0,
            current: currentPage,
            pageSize: pageSize,
            onChange: onPaginationChange
          }}
        ></Table>
      )}
    </>
  )
}
