/**
 * 用户管理页面
 *
 * - 用户列表（分页，支持关键字搜索）
 * - 创建/编辑用户弹窗
 * - 重置密码确认
 * - 启用/禁用、删除
 */

import { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Card,
  Form,
  Input,
  Message,
  Modal,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from '@arco-design/web-react';
// Arco 2.x 中 TableColumnData 已移除，改用 TableColumnProps
import type { TableColumnProps } from '@arco-design/web-react';
import { IconSearch, IconRefresh } from '@arco-design/web-react/icon';
import {
  fetchUsers,
  createUser,
  updateUser,
  resetPassword,
  setUserStatus,
  deleteUser,
} from '@/api/user';
import type { User } from '@/api/user';
import { orgApi } from '@/api/devices';
import type { Organization } from '@/api/devices';
import { Permission } from '@/components/Permission';

const ROLE_OPTIONS = [
  { label: '普通用户', value: 0 },
  { label: '企业管理员', value: 1 },
  { label: '总管理员', value: 2 },
];

export default function UsersPage() {
  // 列表状态
  const [data, setData] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [loading, setLoading] = useState(false);
  const [keyword, setKeyword] = useState('');

  // 组织选项
  const [orgs, setOrgs] = useState<Organization[]>([]);

  // 弹窗状态
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [formValues, setFormValues] = useState({
    phone: '',
    name: '',
    role: 0,
    organization_id: undefined as number | undefined,
    password: '123456',
  });
  const [saving, setSaving] = useState(false);

  // 重置密码弹窗
  const [resetVisible, setResetVisible] = useState(false);
  const [resetUserId, setResetUserId] = useState<number | null>(null);
  const [resetPasswordVal, setResetPasswordVal] = useState('123456');
  const [resetting, setResetting] = useState(false);

  /** 加载组织列表 */
  useEffect(() => {
    orgApi.list().then((res) => setOrgs(res.data || [])).catch(() => {});
  }, []);

  /** 构建查询参数 */
  const buildQuery = useCallback(() => {
    const params: Record<string, string | number> = { page, page_size: pageSize };
    if (keyword.trim()) params.keyword = keyword.trim();
    return params;
  }, [page, pageSize, keyword]);

  /** 加载用户列表 */
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchUsers(buildQuery());
      setData(res.list);
      setTotal(res.total);
    } catch {
      Message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  }, [buildQuery]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  /** 搜索 */
  const handleSearch = () => {
    setPage(1);
    fetchData();
  };

  /** 打开创建弹窗 */
  const handleCreate = () => {
    setEditingUser(null);
    setModalTitle('创建用户');
    setFormValues({ phone: '', name: '', role: 0, organization_id: undefined, password: '123456' });
    setModalVisible(true);
  };

  /** 打开编辑弹窗 */
  const handleEdit = (user: User) => {
    setEditingUser(user);
    setModalTitle('编辑用户');
    setFormValues({
      phone: user.phone,
      name: user.name ?? '',
      role: user.role,
      organization_id: user.organization_id ?? undefined,
      password: '123456',
    });
    setModalVisible(true);
  };

  /** 保存用户 */
  const handleSave = async () => {
    if (editingUser) {
      // 编辑
      if (!formValues.name.trim()) {
        Message.warning('请输入姓名');
        return;
      }
      setSaving(true);
      try {
        await updateUser(editingUser.id, {
          name: formValues.name.trim() || undefined,
          role: formValues.role,
          organization_id: formValues.organization_id ?? null,
        });
        Message.success('更新成功');
        setModalVisible(false);
        fetchData();
      } catch {
        Message.error('更新失败');
      } finally {
        setSaving(false);
      }
    } else {
      // 创建
      if (formValues.phone.length !== 11) {
        Message.warning('请输入11位手机号');
        return;
      }
      setSaving(true);
      try {
        await createUser({
          phone: formValues.phone,
          name: formValues.name.trim() || undefined,
          role: formValues.role,
          organization_id: formValues.role === 1 ? formValues.organization_id : null,
          password: formValues.password !== '123456' ? formValues.password : undefined,
        });
        Message.success('创建成功');
        setModalVisible(false);
        fetchData();
      } catch {
        Message.error('创建失败');
      } finally {
        setSaving(false);
      }
    }
  };

  /** 重置密码弹窗 */
  const handleResetPassword = (user: User) => {
    setResetUserId(user.id);
    setResetPasswordVal('123456');
    setResetVisible(true);
  };

  /** 确认重置密码 */
  const handleResetConfirm = async () => {
    if (resetUserId === null) return;
    setResetting(true);
    try {
      await resetPassword(resetUserId, resetPasswordVal !== '123456' ? resetPasswordVal : undefined);
      Message.success('密码已重置');
      setResetVisible(false);
    } catch {
      Message.error('重置密码失败');
    } finally {
      setResetting(false);
    }
  };

  /** 启用/禁用 */
  const handleToggleStatus = async (user: User) => {
    const newStatus = user.status === 1 ? 0 : 1;
    try {
      await setUserStatus(user.id, newStatus);
      Message.success(newStatus === 1 ? '已启用' : '已禁用');
      fetchData();
    } catch {
      Message.error('操作失败');
    }
  };

  /** 删除用户 */
  const handleDelete = async (id: number) => {
    try {
      await deleteUser(id);
      Message.success('删除成功');
      fetchData();
    } catch {
      Message.error('删除失败');
    }
  };

  /** 表格列 */
  const columns: TableColumnProps<User>[] = [
    { title: '手机号', dataIndex: 'phone', width: 130 },
    { title: '姓名', dataIndex: 'name', width: 120, render: (v: string | null) => v || '-' },
    { title: '角色', dataIndex: 'role_text', width: 110 },
    {
      title: '所属组织',
      dataIndex: 'organization_name',
      width: 150,
      render: (v: string | null) => v || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      width: 240,
      render: (_: unknown, record: User) => (
        <Space>
          <Permission code="user:edit">
            <Button type="text" size="small" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          </Permission>
          <Permission code="user:edit">
            <Button type="text" size="small" onClick={() => handleResetPassword(record)}>
              重置密码
            </Button>
          </Permission>
          <Permission code="user:edit">
            <Button type="text" size="small" onClick={() => handleToggleStatus(record)}>
              {record.status === 1 ? '禁用' : '启用'}
            </Button>
          </Permission>
          <Permission code="user:delete">
            <Popconfirm
              title="确认删除该用户？"
              onOk={() => handleDelete(record.id)}
            >
              <Button type="text" size="small" status="danger">
                删除
              </Button>
            </Popconfirm>
          </Permission>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 头部 */}
        <Space style={{ justifyContent: 'space-between', width: '100%' }}>
          <Typography.Title heading={4} style={{ margin: 0 }}>
            用户管理
          </Typography.Title>
          <Permission code="user:create">
            <Button type="primary" onClick={handleCreate}>
              创建用户
            </Button>
          </Permission>
        </Space>

        {/* 搜索 */}
        <Space>
          <Input.Search
            placeholder="搜索手机号/姓名"
            value={keyword}
            onChange={(v) => setKeyword(v)}
            onSearch={handleSearch}
            style={{ width: 260 }}
            allowClear
          />
          <Button icon={<IconSearch />} onClick={handleSearch}>
            查询
          </Button>
          <Button icon={<IconRefresh />} onClick={() => { setKeyword(''); setPage(1); }}>
            重置
          </Button>
        </Space>

        {/* 表格 — Arco 2.x size 不再接受 "medium"，用 "default" 替代 */}
        <Table
          rowKey="id"
          columns={columns}
          data={data}
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize,
            onChange: setPage,
            showTotal: true,
          }}
          size="default"
        />
      </Space>

      {/* 创建/编辑弹窗 */}
      <Modal
        title={modalTitle}
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSave}
        confirmLoading={saving}
        style={{ width: 520 }}
      >
        <Form layout="vertical">
          {!editingUser && (
            <Form.Item label="手机号" required>
              <Input
                value={formValues.phone}
                onChange={(v) => setFormValues({ ...formValues, phone: v })}
                placeholder="11位手机号"
                maxLength={11}
              />
            </Form.Item>
          )}
          <Form.Item label="姓名">
            <Input
              value={formValues.name}
              onChange={(v) => setFormValues({ ...formValues, name: v })}
              placeholder="姓名（选填）"
            />
          </Form.Item>
          <Form.Item label="角色" required>
            <Select
              value={formValues.role}
              onChange={(v) => setFormValues({ ...formValues, role: v as number })}
              options={ROLE_OPTIONS}
            />
          </Form.Item>
          <Form.Item label="所属组织">
            <Select
              value={formValues.organization_id}
              onChange={(v) => setFormValues({ ...formValues, organization_id: v as number | undefined })}
              options={orgs.map((o) => ({ label: o.name, value: o.id }))}
              placeholder={formValues.role === 1 ? '企业管理员必填' : '选填'}
              allowClear
            />
          </Form.Item>
          {!editingUser && (
            <Form.Item label="初始密码">
              <Input.Password
                value={formValues.password}
                onChange={(v) => setFormValues({ ...formValues, password: v })}
                placeholder="默认123456"
              />
            </Form.Item>
          )}
        </Form>
      </Modal>

      {/* 重置密码弹窗 */}
      <Modal
        title="重置密码"
        visible={resetVisible}
        onCancel={() => setResetVisible(false)}
        onOk={handleResetConfirm}
        confirmLoading={resetting}
        simple
      >
        <Form layout="vertical">
          <Form.Item label="新密码">
            <Input.Password
              value={resetPasswordVal}
              onChange={(v) => setResetPasswordVal(v)}
              placeholder="默认123456"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
