/**
 * KRA - User Management Page
 * Manage system users with CRUD operations
 */
import React, { useState, useRef, useEffect } from 'react';
import {
  PageContainer,
  ProTable,
  ModalForm,
  DrawerForm,
  ProFormText,
  ProFormSelect,
  ProFormSwitch,
} from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag, Switch, Avatar, Space, Cascader, Input, Modal, Form } from 'antd';
import { PlusOutlined, SearchOutlined, ReloadOutlined, CopyOutlined } from '@ant-design/icons';
import {
  getUserList,
  register,
  deleteUser,
  setUserInfo,
  setUserAuthorities,
  resetPassword,
} from '@/services/kratos/user';
import { getAuthorityList } from '@/services/kratos/authority';
import WarningBar from '@/components/WarningBar/WarningBar';
import UserForm from './components/UserForm';
import AuthoritySelect from './components/AuthoritySelect';

interface UserInfo {
  ID: number;
  uuid: string;
  userName: string;
  nickName: string;
  headerImg: string;
  phone: string;
  email: string;
  enable: number;
  authorityId: string;
  authorityIds: string[];
  authority?: {
    authorityId: string;
    authorityName: string;
  };
  authorities?: Array<{
    authorityId: string;
    authorityName: string;
  }>;
}

interface AuthorityOption {
  authorityId: string;
  authorityName: string;
  children?: AuthorityOption[];
}

const UserPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<UserInfo | null>(null);
  const [dialogFlag, setDialogFlag] = useState<'add' | 'edit'>('add');
  const [authOptions, setAuthOptions] = useState<AuthorityOption[]>([]);
  const [resetPwdVisible, setResetPwdVisible] = useState(false);
  const [resetPwdInfo, setResetPwdInfo] = useState<{
    ID: number;
    userName: string;
    nickName: string;
    password: string;
  }>({ ID: 0, userName: '', nickName: '', password: '' });

  // 搜索表单
  const [searchInfo, setSearchInfo] = useState({
    username: '',
    nickname: '',
    phone: '',
    email: '',
  });

  // 初始化角色选项
  useEffect(() => {
    fetchAuthorityOptions();
  }, []);

  const fetchAuthorityOptions = async () => {
    try {
      const res = await getAuthorityList();
      if (res.code === 0) {
        // GVA接口直接返回树形数组，不是分页格式
        const options = buildAuthorityOptions(res.data || []);
        setAuthOptions(options);
      }
    } catch (error) {
      console.error('Failed to fetch authority list:', error);
    }
  };

  // 构建角色树形选项
  const buildAuthorityOptions = (data: any[]): AuthorityOption[] => {
    return data.map((item) => ({
      authorityId: item.authorityId,
      authorityName: item.authorityName,
      children: item.children ? buildAuthorityOptions(item.children) : undefined,
    }));
  };

  // 生成随机密码
  const generateRandomPassword = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let password = '';
    for (let i = 0; i < 12; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setResetPwdInfo((prev) => ({ ...prev, password }));
    navigator.clipboard.writeText(password).then(
      () => message.success('密码已复制到剪贴板'),
      () => message.error('复制失败，请手动复制')
    );
  };

  // 重置密码
  const handleResetPassword = async () => {
    if (!resetPwdInfo.password) {
      message.warning('请输入或生成密码');
      return;
    }
    try {
      const res = await resetPassword({ ID: resetPwdInfo.ID, password: resetPwdInfo.password });
      if (res.code === 0) {
        message.success(res.msg || '密码重置成功');
        setResetPwdVisible(false);
      } else {
        message.error(res.msg || '密码重置失败');
      }
    } catch (error) {
      message.error('密码重置失败');
    }
  };

  // 切换用户启用状态
  const handleSwitchEnable = async (record: UserInfo) => {
    try {
      const res = await setUserInfo({ ...record, enable: record.enable === 1 ? 2 : 1 });
      if (res.code === 0) {
        message.success(`${record.enable === 1 ? '禁用' : '启用'}成功`);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 修改用户角色
  const handleChangeAuthority = async (record: UserInfo, authorityIds: string[]) => {
    try {
      const res = await setUserAuthorities({ ID: record.ID, authorityIds });
      if (res.code === 0) {
        message.success('角色设置成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('角色设置失败');
    }
  };

  // 删除用户
  const handleDelete = async (record: UserInfo) => {
    try {
      const res = await deleteUser({ id: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 表格列定义
  const columns: ProColumns<UserInfo>[] = [
    {
      title: '头像',
      dataIndex: 'headerImg',
      width: 80,
      search: false,
      render: (_, record) => (
        <Avatar src={record.headerImg} size={40}>
          {record.nickName?.charAt(0) || record.userName?.charAt(0)}
        </Avatar>
      ),
    },
    {
      title: 'ID',
      dataIndex: 'ID',
      width: 60,
      search: false,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 120,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 140,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 180,
    },
    {
      title: '用户角色',
      dataIndex: 'authorityIds',
      width: 200,
      search: false,
      render: (_, record) => (
        <AuthoritySelect
          value={record.authorityIds || record.authorities?.map((a) => a.authorityId) || []}
          options={authOptions}
          onChange={(ids) => handleChangeAuthority(record, ids)}
        />
      ),
    },
    {
      title: '启用',
      dataIndex: 'enable',
      width: 80,
      search: false,
      render: (_, record) => (
        <Switch
          checked={record.enable === 1}
          onChange={() => handleSwitchEnable(record)}
        />
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Popconfirm
          key="delete"
          title="确定要删除吗?"
          onConfirm={() => handleDelete(record)}
        >
          <a style={{ color: '#ff4d4f' }}>删除</a>
        </Popconfirm>,
        <a
          key="edit"
          onClick={() => {
            setCurrentRow(record);
            setDialogFlag('edit');
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="resetPwd"
          onClick={() => {
            setResetPwdInfo({
              ID: record.ID,
              userName: record.userName,
              nickName: record.nickName,
              password: '',
            });
            setResetPwdVisible(true);
          }}
        >
          重置密码
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <WarningBar title="注：右上角头像下拉可切换角色" type="info" />
      <ProTable<UserInfo>
        actionRef={actionRef}
        columns={columns}
        rowKey="ID"
        scroll={{ x: 1200 }}
        request={async (params) => {
          const res = await getUserList({
            page: params.current || 1,
            pageSize: params.pageSize || 10,
            username: params.userName,
            nickname: params.nickName,
            phone: params.phone,
            email: params.email,
          });
          // 处理 authorityIds
          const list = (res.data?.list || []).map((user: UserInfo) => ({
            ...user,
            authorityIds: user.authorities?.map((a) => a.authorityId) || [],
          }));
          return {
            data: list,
            total: res.data?.total || 0,
            success: res.code === 0,
          };
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '30', '50', '100'],
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCurrentRow(null);
              setDialogFlag('add');
              setDrawerVisible(true);
            }}
          >
            新增用户
          </Button>,
        ]}
        search={{
          labelWidth: 'auto',
        }}
      />

      {/* 用户表单抽屉 */}
      <UserForm
        visible={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
        }}
        onSuccess={() => {
          setDrawerVisible(false);
          setCurrentRow(null);
          actionRef.current?.reload();
        }}
        initialValues={currentRow}
        dialogFlag={dialogFlag}
        authOptions={authOptions}
      />

      {/* 重置密码对话框 */}
      <Modal
        title="重置密码"
        open={resetPwdVisible}
        onCancel={() => setResetPwdVisible(false)}
        onOk={handleResetPassword}
        width={500}
      >
        <Form layout="horizontal" labelCol={{ span: 6 }}>
          <Form.Item label="用户账号">
            <Input value={resetPwdInfo.userName} disabled />
          </Form.Item>
          <Form.Item label="用户昵称">
            <Input value={resetPwdInfo.nickName} disabled />
          </Form.Item>
          <Form.Item label="新密码">
            <Space.Compact style={{ width: '100%' }}>
              <Input.Password
                value={resetPwdInfo.password}
                onChange={(e) =>
                  setResetPwdInfo((prev) => ({ ...prev, password: e.target.value }))
                }
                placeholder="请输入新密码"
              />
              <Button type="primary" onClick={generateRandomPassword}>
                生成随机密码
              </Button>
            </Space.Compact>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserPage;
