import React, { useCallback, useEffect, useMemo, useState } from 'react'
import {
  App,
  Button,
  Card,
  DatePicker,
  Drawer,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
} from 'antd'
import { DeleteOutlined, PlusOutlined, ReloadOutlined, TeamOutlined, UserAddOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs, { type Dayjs } from 'dayjs'
import { useSelector } from 'react-redux'
import apiClient from '../../services/apiClient'
import { selectUser } from '../../store/slices/authSlice'


type UserRole = 'superadmin' | 'leader' | 'member'
type GroupExpirePreset = 'three_days' | 'one_week' | 'one_month' | 'permanent' | 'custom'

interface GroupRecord {
  id: string
  name: string
  createdAt?: string
  createdBy?: string
  expiresAt?: string
  allowBuild?: boolean
  isExpired?: boolean
}

interface UserRecord {
  id: string
  username: string
  role: UserRole
  groupId?: string
  groupName?: string
  createdAt?: string
  lastLoginAt?: string
}

const roleLabelMap: Record<UserRole, string> = {
  superadmin: '超级管理员',
  leader: '组长',
  member: '组员',
}

const roleColorMap: Record<UserRole, string> = {
  superadmin: 'gold',
  leader: 'processing',
  member: 'default',
}

const formatTime = (value?: string): string => {
  if (!value) return '-'
  const date = dayjs(value)
  if (!date.isValid()) return '-'
  return date.format('YYYY-MM-DD HH:mm:ss')
}

const formatGroupExpire = (group: GroupRecord): React.ReactNode => {
  if (!group.expiresAt) {
    return <Tag color="blue">永久有效</Tag>
  }

  const date = dayjs(group.expiresAt)
  if (!date.isValid()) {
    return <Tag>时间异常</Tag>
  }

  const expired = group.isExpired || date.isBefore(dayjs())
  if (expired) {
    return <Tag color="red">已过期</Tag>
  }

  return <Tag color="green">{date.format('YYYY-MM-DD HH:mm')}</Tag>
}

const TenantManagement: React.FC = () => {
  const { message, modal } = App.useApp()
  const currentUser = useSelector(selectUser)
  const currentRole = currentUser?.role || 'member'
  const isSuperAdmin = currentRole === 'superadmin'
  const isLeader = currentRole === 'leader'

  const [groups, setGroups] = useState<GroupRecord[]>([])
  const [groupsLoading, setGroupsLoading] = useState(false)

  const [createGroupVisible, setCreateGroupVisible] = useState(false)
  const [creatingGroup, setCreatingGroup] = useState(false)
  const [newGroupName, setNewGroupName] = useState('')
  const [newGroupExpiresAt, setNewGroupExpiresAt] = useState<Dayjs | null>(null)
  const [newGroupExpirePreset, setNewGroupExpirePreset] = useState<GroupExpirePreset>('permanent')
  const [newGroupAllowBuild, setNewGroupAllowBuild] = useState(true)
  const [editGroupExpireVisible, setEditGroupExpireVisible] = useState(false)
  const [editingGroup, setEditingGroup] = useState<GroupRecord | null>(null)
  const [editGroupExpiresAt, setEditGroupExpiresAt] = useState<Dayjs | null>(null)
  const [editGroupExpirePreset, setEditGroupExpirePreset] = useState<GroupExpirePreset>('permanent')
  const [updatingGroupExpire, setUpdatingGroupExpire] = useState(false)

  const [memberDrawerVisible, setMemberDrawerVisible] = useState(false)
  const [selectedGroup, setSelectedGroup] = useState<GroupRecord | null>(null)
  const [members, setMembers] = useState<UserRecord[]>([])
  const [membersLoading, setMembersLoading] = useState(false)
  const [deletingMemberId, setDeletingMemberId] = useState<string | null>(null)
  const [updatingGroupId, setUpdatingGroupId] = useState<string | null>(null)
  const [updatingMemberRoleId, setUpdatingMemberRoleId] = useState<string | null>(null)

  const [createMemberVisible, setCreateMemberVisible] = useState(false)
  const [newMemberUsername, setNewMemberUsername] = useState('')
  const [newMemberPassword, setNewMemberPassword] = useState('')
  const [newMemberRole, setNewMemberRole] = useState<'leader' | 'member'>('member')
  const [creatingMember, setCreatingMember] = useState(false)

  const loadGroups = useCallback(async () => {
    setGroupsLoading(true)
    try {
      const result = await apiClient.get<{ success: boolean, groups: GroupRecord[] }>('/api/auth/groups')
      setGroups(Array.isArray(result.groups) ? result.groups : [])
    } catch (error: any) {
      message.error(error?.message || '获取组列表失败')
    } finally {
      setGroupsLoading(false)
    }
  }, [message])

  const loadGroupMembers = useCallback(async (groupId: string) => {
    if (!groupId) return
    setMembersLoading(true)
    try {
      const result = await apiClient.get<{ success: boolean, members: UserRecord[] }>(`/api/groups/${groupId}/members`)
      setMembers(Array.isArray(result.members) ? result.members : [])
    } catch (error: any) {
      message.error(error?.message || '获取组成员失败')
      setMembers([])
    } finally {
      setMembersLoading(false)
    }
  }, [message])

  useEffect(() => {
    void loadGroups()
  }, [loadGroups])

  const openCreateGroupModal = () => {
    setNewGroupName('')
    setNewGroupExpiresAt(null)
    setNewGroupExpirePreset('permanent')
    setNewGroupAllowBuild(true)
    setCreateGroupVisible(true)
  }

  const calcExpireByPreset = (preset: GroupExpirePreset): Dayjs | null => {
    if (preset === 'permanent') return null
    if (preset === 'three_days') return dayjs().add(3, 'day')
    if (preset === 'one_week') return dayjs().add(7, 'day')
    if (preset === 'one_month') return dayjs().add(1, 'month')
    return dayjs().add(3, 'day')
  }

  const applyGroupExpirePreset = (preset: GroupExpirePreset) => {
    setNewGroupExpirePreset(preset)
    if (preset === 'custom') {
      if (!newGroupExpiresAt) {
        setNewGroupExpiresAt(calcExpireByPreset('three_days'))
      }
      return
    }
    setNewGroupExpiresAt(calcExpireByPreset(preset))
  }

  const submitCreateGroup = async () => {
    const groupName = newGroupName.trim()
    if (!groupName) {
      message.warning('请输入组名')
      return
    }

    if (newGroupExpiresAt && newGroupExpiresAt.isBefore(dayjs())) {
      message.warning('过期时间必须晚于当前时间')
      return
    }
    if (newGroupExpirePreset === 'custom' && !newGroupExpiresAt) {
      message.warning('请选择自定义过期时间')
      return
    }

    setCreatingGroup(true)
    try {
      const result = await apiClient.post<{ success: boolean, message?: string }>('/api/admin/groups', {
        name: groupName,
        expiresAt: newGroupExpiresAt ? newGroupExpiresAt.toISOString() : undefined,
        allowBuild: newGroupAllowBuild,
      })

      if (!result.success) {
        message.error(result.message || '新建组失败')
        return
      }

      message.success('新建组成功')
      setCreateGroupVisible(false)
      await loadGroups()
    } catch (error: any) {
      message.error(error?.message || '新建组失败')
    } finally {
      setCreatingGroup(false)
    }
  }

  const confirmDeleteGroup = (group: GroupRecord) => {
    modal.confirm({
      title: `确认删除组「${group.name}」？`,
      content: '删除前请先清空该组成员；组设备不会被删除。',
      okText: '删除组',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          const result = await apiClient.delete<{ success: boolean, message?: string }>(`/api/admin/groups/${group.id}`)
          if (!result.success) {
            message.error(result.message || '删除组失败')
            return
          }
          message.success('删除组成功')
          if (selectedGroup?.id === group.id) {
            setMemberDrawerVisible(false)
            setSelectedGroup(null)
            setMembers([])
          }
          await loadGroups()
        } catch (error: any) {
          message.error(error?.message || '删除组失败')
        }
      }
    })
  }

  const openMemberDrawer = async (group: GroupRecord) => {
    setSelectedGroup(group)
    setMemberDrawerVisible(true)
    await loadGroupMembers(group.id)
  }

  const removeMember = async (member: UserRecord) => {
    if (!selectedGroup) return

    setDeletingMemberId(member.id)
    try {
      const result = await apiClient.delete<{ success: boolean, message?: string }>(`/api/groups/${selectedGroup.id}/members/${member.id}`)
      if (!result.success) {
        message.error(result.message || '删除成员失败')
        return
      }
      message.success('删除成员成功')
      await loadGroupMembers(selectedGroup.id)
      await loadGroups()
    } catch (error: any) {
      message.error(error?.message || '删除成员失败')
    } finally {
      setDeletingMemberId(null)
    }
  }

  const updateGroupAllowBuild = async (group: GroupRecord, allowBuild: boolean) => {
    if (!isSuperAdmin) return
    setUpdatingGroupId(group.id)
    try {
      const result = await apiClient.put<{ success: boolean, message?: string }>(`/api/admin/groups/${group.id}`, {
        allowBuild,
      })
      if (!result.success) {
        message.error(result.message || '更新组构建权限失败')
        return
      }
      message.success(`已${allowBuild ? '开启' : '关闭'}组构建权限`)
      setSelectedGroup((prev) => {
        if (!prev || prev.id !== group.id) return prev
        return { ...prev, allowBuild }
      })
      await loadGroups()
      if (selectedGroup?.id === group.id) {
        await loadGroupMembers(group.id)
      }
    } catch (error: any) {
      message.error(error?.message || '更新组构建权限失败')
    } finally {
      setUpdatingGroupId(null)
    }
  }

  const openEditGroupExpireModal = (group: GroupRecord) => {
    setEditingGroup(group)
    if (!group.expiresAt) {
      setEditGroupExpirePreset('permanent')
      setEditGroupExpiresAt(null)
    } else {
      const expires = dayjs(group.expiresAt)
      if (expires.isValid()) {
        setEditGroupExpirePreset('custom')
        setEditGroupExpiresAt(expires)
      } else {
        setEditGroupExpirePreset('permanent')
        setEditGroupExpiresAt(null)
      }
    }
    setEditGroupExpireVisible(true)
  }

  const applyEditGroupExpirePreset = (preset: GroupExpirePreset) => {
    setEditGroupExpirePreset(preset)
    if (preset === 'custom') {
      if (!editGroupExpiresAt) {
        setEditGroupExpiresAt(calcExpireByPreset('three_days'))
      }
      return
    }
    setEditGroupExpiresAt(calcExpireByPreset(preset))
  }

  const submitEditGroupExpire = async () => {
    if (!isSuperAdmin || !editingGroup) return

    const targetExpiresAt = editGroupExpirePreset === 'permanent'
      ? null
      : (editGroupExpiresAt ? editGroupExpiresAt.toISOString() : null)

    if (editGroupExpirePreset === 'custom' && !targetExpiresAt) {
      message.warning('请选择自定义过期时间')
      return
    }

    if (targetExpiresAt && dayjs(targetExpiresAt).isBefore(dayjs())) {
      message.warning('过期时间必须晚于当前时间')
      return
    }

    setUpdatingGroupExpire(true)
    const currentEditingGroupId = editingGroup.id
    try {
      const result = await apiClient.put<{ success: boolean, message?: string, group?: GroupRecord }>(
        `/api/admin/groups/${currentEditingGroupId}`,
        { expiresAt: targetExpiresAt }
      )

      if (!result.success) {
        message.error(result.message || '更新组有效期失败')
        return
      }

      message.success('组有效期更新成功')
      setEditGroupExpireVisible(false)
      setEditingGroup(null)

      setSelectedGroup((prev) => {
        if (!prev || prev.id !== currentEditingGroupId) return prev
        if (result.group) {
          return { ...prev, ...result.group }
        }
        return {
          ...prev,
          expiresAt: targetExpiresAt || undefined,
          isExpired: false,
        }
      })

      await loadGroups()
      if (selectedGroup?.id === currentEditingGroupId) {
        await loadGroupMembers(currentEditingGroupId)
      }
    } catch (error: any) {
      message.error(error?.message || '更新组有效期失败')
    } finally {
      setUpdatingGroupExpire(false)
    }
  }

  const updateMemberRole = async (member: UserRecord, role: 'leader' | 'member') => {
    if (!isSuperAdmin || !selectedGroup) return
    setUpdatingMemberRoleId(member.id)
    try {
      const result = await apiClient.put<{ success: boolean, message?: string }>(
        `/api/groups/${selectedGroup.id}/members/${member.id}/role`,
        { role }
      )
      if (!result.success) {
        message.error(result.message || '更新成员角色失败')
        return
      }
      message.success(role === 'leader' ? '任命组长成功' : '已取消组长')
      await loadGroupMembers(selectedGroup.id)
      await loadGroups()
    } catch (error: any) {
      message.error(error?.message || '更新成员角色失败')
    } finally {
      setUpdatingMemberRoleId(null)
    }
  }

  const openCreateMemberModal = () => {
    setNewMemberUsername('')
    setNewMemberPassword('')
    setNewMemberRole('member')
    setCreateMemberVisible(true)
  }

  const submitCreateMember = async () => {
    if (!selectedGroup) return

    const username = newMemberUsername.trim()
    if (!username) {
      message.warning('请输入成员账号')
      return
    }
    if (!newMemberPassword || newMemberPassword.length < 6) {
      message.warning('成员密码至少 6 位')
      return
    }

    setCreatingMember(true)
    try {
      const result = await apiClient.post<{ success: boolean, message?: string }>(`/api/groups/${selectedGroup.id}/members`, {
        username,
        password: newMemberPassword,
        role: newMemberRole,
      })

      if (!result.success) {
        message.error(result.message || '添加成员失败')
        return
      }

      message.success('添加成员成功')
      setCreateMemberVisible(false)
      await loadGroupMembers(selectedGroup.id)
      await loadGroups()
    } catch (error: any) {
      message.error(error?.message || '添加成员失败')
    } finally {
      setCreatingMember(false)
    }
  }

  const sortedGroups = useMemo(() => {
    return [...groups].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
  }, [groups])

  const groupColumns: ColumnsType<GroupRecord> = [
    {
      title: '组名',
      dataIndex: 'name',
      key: 'name',
      width: 220,
      render: (name: string) => (
        <Space>
          <TeamOutlined />
          <span>{name}</span>
        </Space>
      ),
    },
    {
      title: '构建包权限',
      dataIndex: 'allowBuild',
      key: 'allowBuild',
      width: 140,
      render: (allowBuild: boolean | undefined, row: GroupRecord) => {
        if (!isSuperAdmin) {
          return allowBuild === false
            ? <Tag color="red">禁用</Tag>
            : <Tag color="green">允许</Tag>
        }
        return (
          <Switch
            checked={allowBuild !== false}
            checkedChildren="开"
            unCheckedChildren="关"
            loading={updatingGroupId === row.id}
            onChange={(checked) => {
              void updateGroupAllowBuild(row, checked)
            }}
          />
        )
      },
    },
    {
      title: '有效期',
      key: 'expiresAt',
      width: 180,
      render: (_: unknown, row: GroupRecord) => formatGroupExpire(row),
    },
    {
      title: '创建者',
      dataIndex: 'createdBy',
      key: 'createdBy',
      width: 160,
      render: (createdBy: string) => createdBy || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt: string) => formatTime(createdAt),
    },
    {
      title: '操作',
      key: 'actions',
      width: 280,
      fixed: 'right',
      render: (_: unknown, row: GroupRecord) => (
        <Space>
          <Button size="small" onClick={() => void openMemberDrawer(row)}>详情</Button>
          {isSuperAdmin ? (
            <>
              <Button size="small" onClick={() => openEditGroupExpireModal(row)}>
                调整有效期
              </Button>
              <Button
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={() => confirmDeleteGroup(row)}
              >
                删除组
              </Button>
            </>
          ) : null}
        </Space>
      ),
    },
  ]

  const memberColumns: ColumnsType<UserRecord> = [
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
      width: 180,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 110,
      render: (role: UserRole) => <Tag color={roleColorMap[role]}>{roleLabelMap[role]}</Tag>,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      width: 170,
      render: (value?: string) => formatTime(value),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 170,
      render: (value?: string) => formatTime(value),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_: unknown, row: UserRecord) => {
        const canDeleteByRole = isSuperAdmin || (isLeader && row.role === 'member')
        const isSelf = row.id === currentUser?.id
        const canRoleAction = isSuperAdmin && !isSelf

        const roleAction = canRoleAction ? (
          row.role === 'leader' ? (
            <Button
              type="link"
              size="small"
              loading={updatingMemberRoleId === row.id}
              onClick={() => void updateMemberRole(row, 'member')}
            >
              取消组长
            </Button>
          ) : (
            <Button
              type="link"
              size="small"
              loading={updatingMemberRoleId === row.id}
              onClick={() => void updateMemberRole(row, 'leader')}
            >
              任命组长
            </Button>
          )
        ) : null

        const deleteAction = (!canDeleteByRole || isSelf) ? null : (
          <Popconfirm
            title={`确认删除成员 ${row.username}？`}
            okText="删除"
            cancelText="取消"
            onConfirm={() => void removeMember(row)}
          >
            <Button
              type="link"
              size="small"
              danger
              loading={deletingMemberId === row.id}
            >
              删除成员
            </Button>
          </Popconfirm>
        )

        if (!roleAction && !deleteAction) {
          return <Typography.Text type="secondary">-</Typography.Text>
        }

        return <Space size={4}>{roleAction}{deleteAction}</Space>
      },
    },
  ]

  const tenantHint = isSuperAdmin
    ? '你可创建/删除组，并管理任意组成员。'
    : '你当前为组长，只能查看本组并删除本组组员。'

  return (
    <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card
        title="租户管理"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={() => void loadGroups()}>
              刷新
            </Button>
            {isSuperAdmin ? (
              <Button type="primary" icon={<PlusOutlined />} onClick={openCreateGroupModal}>
                新建组
              </Button>
            ) : null}
          </Space>
        }
      >
        <Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
          {tenantHint}
        </Typography.Paragraph>

        <Table
          rowKey="id"
          loading={groupsLoading}
          columns={groupColumns}
          dataSource={sortedGroups}
          pagination={{ pageSize: 10, showSizeChanger: true }}
          scroll={{ x: 980 }}
        />
      </Card>

      <Modal
        title="新建组"
        open={createGroupVisible}
        onCancel={() => {
          if (creatingGroup) return
          setCreateGroupVisible(false)
        }}
        onOk={() => void submitCreateGroup()}
        confirmLoading={creatingGroup}
        okText="创建"
        cancelText="取消"
        destroyOnClose
      >
        <Space direction="vertical" style={{ width: '100%' }} size={12}>
          <Input
            value={newGroupName}
            onChange={(event) => setNewGroupName(event.target.value)}
            placeholder="请输入组名"
            maxLength={64}
          />

          <Space direction="vertical" style={{ width: '100%' }} size={4}>
            <Typography.Text>过期策略</Typography.Text>
            <Select<GroupExpirePreset>
              value={newGroupExpirePreset}
              onChange={(value) => applyGroupExpirePreset(value)}
              options={[
                { label: '3天后过期', value: 'three_days' },
                { label: '一周后过期', value: 'one_week' },
                { label: '一个月后过期', value: 'one_month' },
                { label: '永久有效', value: 'permanent' },
                { label: '自定义时间', value: 'custom' },
              ]}
            />
          </Space>

          <Space direction="vertical" style={{ width: '100%' }} size={4}>
            <Typography.Text>组过期时间（可选）</Typography.Text>
            <DatePicker
              showTime
              style={{ width: '100%' }}
              value={newGroupExpiresAt}
              onChange={(value) => {
                setNewGroupExpiresAt(value)
                if (value) {
                  setNewGroupExpirePreset('custom')
                } else {
                  setNewGroupExpirePreset('permanent')
                }
              }}
              placeholder="不设置则永久有效"
              disabled={newGroupExpirePreset !== 'custom'}
              allowClear
            />
          </Space>

          <Space align="center" style={{ width: '100%', justifyContent: 'space-between' }}>
            <Typography.Text>允许该组构建 APK</Typography.Text>
            <Switch checked={newGroupAllowBuild} onChange={setNewGroupAllowBuild} />
          </Space>
        </Space>
      </Modal>

      <Drawer
        title={selectedGroup ? `组成员 · ${selectedGroup.name}` : '组成员'}
        width={760}
        open={memberDrawerVisible}
        onClose={() => {
          setMemberDrawerVisible(false)
          setSelectedGroup(null)
          setMembers([])
        }}
        extra={
          isSuperAdmin && selectedGroup ? (
            <Button type="primary" icon={<UserAddOutlined />} onClick={openCreateMemberModal}>
              添加成员
            </Button>
          ) : null
        }
      >
        {selectedGroup ? (
          <Space direction="vertical" style={{ width: '100%' }} size={12}>
            <Card size="small">
              <Space direction="vertical" size={6}>
                <Typography.Text>组名：{selectedGroup.name}</Typography.Text>
                {isSuperAdmin ? (
                  <Space align="center">
                    <Typography.Text>构建权限：</Typography.Text>
                    <Switch
                      checked={selectedGroup.allowBuild !== false}
                      checkedChildren="开"
                      unCheckedChildren="关"
                      loading={updatingGroupId === selectedGroup.id}
                      onChange={(checked) => {
                        void updateGroupAllowBuild(selectedGroup, checked)
                      }}
                    />
                  </Space>
                ) : (
                  <Typography.Text>
                    构建权限：{selectedGroup.allowBuild === false ? '禁用' : '允许'}
                  </Typography.Text>
                )}
                <Typography.Text>
                  过期状态：{selectedGroup.expiresAt ? formatTime(selectedGroup.expiresAt) : '永久有效'}
                </Typography.Text>
                {isSuperAdmin ? (
                  <Button
                    type="link"
                    size="small"
                    style={{ padding: 0, width: 'fit-content' }}
                    onClick={() => openEditGroupExpireModal(selectedGroup)}
                  >
                    调整该组有效期
                  </Button>
                ) : null}
              </Space>
            </Card>

            <Table
              rowKey="id"
              loading={membersLoading}
              columns={memberColumns}
              dataSource={members}
              pagination={{ pageSize: 8, showSizeChanger: true }}
              scroll={{ x: 760 }}
            />
          </Space>
        ) : null}
      </Drawer>

      <Modal
        title={editingGroup ? `调整有效期 · ${editingGroup.name}` : '调整有效期'}
        open={editGroupExpireVisible}
        onCancel={() => {
          if (updatingGroupExpire) return
          setEditGroupExpireVisible(false)
          setEditingGroup(null)
        }}
        onOk={() => void submitEditGroupExpire()}
        confirmLoading={updatingGroupExpire}
        okText="保存"
        cancelText="取消"
        destroyOnClose
      >
        <Space direction="vertical" style={{ width: '100%' }} size={12}>
          <Space direction="vertical" style={{ width: '100%' }} size={4}>
            <Typography.Text>过期策略</Typography.Text>
            <Select<GroupExpirePreset>
              value={editGroupExpirePreset}
              onChange={(value) => applyEditGroupExpirePreset(value)}
              options={[
                { label: '3天后过期', value: 'three_days' },
                { label: '一周后过期', value: 'one_week' },
                { label: '一个月后过期', value: 'one_month' },
                { label: '永久有效', value: 'permanent' },
                { label: '自定义时间', value: 'custom' },
              ]}
            />
          </Space>

          <Space direction="vertical" style={{ width: '100%' }} size={4}>
            <Typography.Text>组过期时间（可选）</Typography.Text>
            <DatePicker
              showTime
              style={{ width: '100%' }}
              value={editGroupExpiresAt}
              onChange={(value) => {
                setEditGroupExpiresAt(value)
                if (value) {
                  setEditGroupExpirePreset('custom')
                } else {
                  setEditGroupExpirePreset('permanent')
                }
              }}
              placeholder="不设置则永久有效"
              disabled={editGroupExpirePreset !== 'custom'}
              allowClear
            />
          </Space>

          <Typography.Text type="secondary">
            组过期只影响登录，不会删除组设备与成员数据。
          </Typography.Text>
        </Space>
      </Modal>

      <Modal
        title={selectedGroup ? `添加成员到 ${selectedGroup.name}` : '添加成员'}
        open={createMemberVisible}
        onCancel={() => {
          if (creatingMember) return
          setCreateMemberVisible(false)
        }}
        onOk={() => void submitCreateMember()}
        confirmLoading={creatingMember}
        okText="添加"
        cancelText="取消"
        destroyOnClose
      >
        <Space direction="vertical" style={{ width: '100%' }} size={12}>
          <Input
            value={newMemberUsername}
            onChange={(event) => setNewMemberUsername(event.target.value)}
            placeholder="请输入成员账号"
            maxLength={64}
          />
          <Input.Password
            value={newMemberPassword}
            onChange={(event) => setNewMemberPassword(event.target.value)}
            placeholder="请输入成员密码（至少 6 位）"
          />
          <Select<'leader' | 'member'>
            value={newMemberRole}
            onChange={(value) => setNewMemberRole(value)}
            options={[
              { label: '组员', value: 'member' },
              { label: '组长', value: 'leader' },
            ]}
          />
          <Typography.Text type="secondary">
            同一组仅允许 1 位组长；如果该组已有组长，系统会拒绝任命。
          </Typography.Text>
        </Space>
      </Modal>
    </div>
  )
}

export default TenantManagement
