import { useCallback, useEffect, useMemo, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { authorityApi, userApi } from '@/lib/api'
import { flattenAuthorities } from '@/lib/tree'
import type { Authority, UserInfo } from '@/types/system'

type UserSearch = {
  username?: string
  nickName?: string
  phone?: string
  email?: string
}

export function UserManagementPage() {
  const [searchForm] = Form.useForm<UserSearch>()
  const [editForm] = Form.useForm()
  const [passwordForm] = Form.useForm()
  const [users, setUsers] = useState<UserInfo[]>([])
  const [authorities, setAuthorities] = useState<Authority[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [modalOpen, setModalOpen] = useState(false)
  const [passwordOpen, setPasswordOpen] = useState(false)
  const [editingUser, setEditingUser] = useState<UserInfo | null>(null)
  const [saving, setSaving] = useState(false)
  const [passwordSaving, setPasswordSaving] = useState(false)

  const authorityOptions = useMemo(
    () =>
      flattenAuthorities(authorities).map((item) => ({
        label: `${'　'.repeat(item.depth)}${item.authorityName} (${item.authorityId})`,
        value: item.authorityId,
      })),
    [authorities],
  )

  const loadAuthorities = useCallback(async () => {
    const response = await authorityApi.getAuthorityList()
    setAuthorities(response.data)
  }, [])

  const loadUsers = useCallback(async () => {
    setLoading(true)
    try {
      const values = searchForm.getFieldsValue()
      const response = await userApi.getUserList({
        page,
        pageSize,
        ...values,
      })
      setUsers(response.data.list)
      setTotal(response.data.total)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, searchForm])

  useEffect(() => {
    loadAuthorities()
  }, [loadAuthorities])

  useEffect(() => {
    loadUsers()
  }, [loadUsers])

  const openCreate = () => {
    setEditingUser(null)
    editForm.resetFields()
    editForm.setFieldsValue({
      enable: true,
      authorityIds: [],
    })
    setModalOpen(true)
  }

  const openEdit = (record: UserInfo) => {
    setEditingUser(record)
    editForm.setFieldsValue({
      userName: record.userName,
      nickName: record.nickName,
      phone: record.phone,
      email: record.email,
      headerImg: record.headerImg,
      authorityIds:
        record.authorities?.map((item) => item.authorityId) ||
        (record.authorityId ? [record.authorityId] : []),
      enable: (record.enable || 1) === 1,
    })
    setModalOpen(true)
  }

  const saveUser = async () => {
    const values = await editForm.validateFields()
    const authorityIds: number[] = values.authorityIds || []
    if (!authorityIds.length) {
      message.warning('至少选择一个角色')
      return
    }

    setSaving(true)
    try {
      const payload = {
        ID: editingUser?.ID,
        userName: values.userName,
        password: values.password,
        nickName: values.nickName,
        phone: values.phone,
        email: values.email,
        headerImg: values.headerImg,
        authorityId: authorityIds[0],
        authorityIds,
        enable: values.enable ? 1 : 2,
      }

      if (editingUser) {
        await userApi.updateUser(payload)
        message.success('用户信息已更新')
      } else {
        await userApi.register(payload)
        message.success('用户已创建')
      }

      setModalOpen(false)
      loadUsers()
    } finally {
      setSaving(false)
    }
  }

  const deleteUser = (record: UserInfo) => {
    Modal.confirm({
      title: `删除用户 ${record.userName}`,
      content: '删除后无法恢复。',
      okText: '删除',
      okButtonProps: { danger: true },
      onOk: async () => {
        await userApi.deleteUser(record.ID)
        message.success('用户已删除')
        loadUsers()
      },
    })
  }

  const openResetPassword = (record: UserInfo) => {
    setEditingUser(record)
    passwordForm.resetFields()
    setPasswordOpen(true)
  }

  const savePassword = async () => {
    const values = await passwordForm.validateFields()
    if (!editingUser) {
      return
    }

    setPasswordSaving(true)
    try {
      await userApi.resetPassword({
        ID: editingUser.ID,
        password: values.password,
      })
      message.success('密码已重置')
      setPasswordOpen(false)
    } finally {
      setPasswordSaving(false)
    }
  }

  const columns: ColumnsType<UserInfo> = [
    {
      title: 'ID',
      dataIndex: 'ID',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 140,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      width: 140,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 150,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 220,
    },
    {
      title: '角色',
      width: 260,
      render: (_, record) => (
        <Space wrap>
          {(record.authorities?.length ? record.authorities : record.authority ? [record.authority] : []).map((item) => (
            <Tag key={item.authorityId}>{item.authorityName}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      width: 100,
      render: (_, record) => (
        <Tag color={(record.enable || 1) === 1 ? 'green' : 'red'}>
          {(record.enable || 1) === 1 ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 220,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => openResetPassword(record)}>
            重置密码
          </Button>
          <Button danger type="link" onClick={() => deleteUser(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              用户管理
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              接口来源：`/user/*` 与 `/authority/getAuthorityList`。首版重点覆盖用户列表、角色集合和密码重置。
            </Typography.Paragraph>
          </div>
          <Button type="primary" onClick={openCreate}>
            新建用户
          </Button>
        </div>
        <Form form={searchForm} layout="vertical" onFinish={() => { setPage(1); loadUsers() }}>
          <Row gutter={[16, 0]}>
            <Col xs={24} md={6}>
              <Form.Item name="username" label="用户名">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="nickName" label="昵称">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="phone" label="手机号">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={6}>
              <Form.Item name="email" label="邮箱">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              onClick={() => {
                searchForm.resetFields()
                setPage(1)
                loadUsers()
              }}
            >
              重置
            </Button>
          </Space>
        </Form>
      </Card>
      <Card className="glass-panel page-panel">
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={users}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          }}
        />
      </Card>

      <Modal
        open={modalOpen}
        title={editingUser ? '编辑用户' : '新建用户'}
        onCancel={() => setModalOpen(false)}
        onOk={saveUser}
        confirmLoading={saving}
        width={720}
      >
        <Form form={editForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="userName" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input disabled={Boolean(editingUser)} />
              </Form.Item>
            </Col>
            {!editingUser ? (
              <Col span={12}>
                <Form.Item name="password" label="登录密码" rules={[{ required: true, min: 6, message: '至少 6 位' }]}>
                  <Input.Password />
                </Form.Item>
              </Col>
            ) : null}
            <Col span={12}>
              <Form.Item name="nickName" label="昵称" rules={[{ required: true, message: '请输入昵称' }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="phone" label="手机号">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="邮箱">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="headerImg" label="头像 URL">
                <Input />
              </Form.Item>
            </Col>
            <Col span={18}>
              <Form.Item name="authorityIds" label="角色集合" rules={[{ required: true, message: '请选择角色' }]}>
                <Select mode="multiple" options={authorityOptions} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="enable" label="启用" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        open={passwordOpen}
        title={`重置密码${editingUser ? ` · ${editingUser.userName}` : ''}`}
        onCancel={() => setPasswordOpen(false)}
        onOk={savePassword}
        confirmLoading={passwordSaving}
      >
        <Form form={passwordForm} layout="vertical">
          <Form.Item name="password" label="新密码" rules={[{ required: true, min: 6, message: '新密码至少 6 位' }]}>
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
