/**
 * @name 员工管理
 */
import React, { useState, useMemo, forwardRef, useImperativeHandle } from 'react';
import { 
    Layout, Card, Row, Col, Statistic, Tree, Input, Table, 
    Button, Space, Tag, Avatar, Modal, Form, Select, 
    Typography, Dropdown, message, theme, Divider, Empty 
} from 'antd';
import { 
    UserOutlined, SyncOutlined, EditOutlined, 
    RestOutlined, MoreOutlined, SearchOutlined,
    CheckCircleOutlined, StopOutlined, LogoutOutlined,
    SafetyCertificateOutlined, TeamOutlined, DeploymentUnitOutlined
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';
import type { AxureProps, AxureHandle } from '../../common/axure-types';
import { MENU_ITEMS, resolveMenuTarget } from '../../common/menu';
import SideMenu from '../../components/side-menu';

const { Sider, Content } = Layout;
const { Search } = Input;
const { Text } = Typography;
const { Option } = Select;

// --- Mock Data ---

const defaultStats = {
    total: 1245,
    active: 1100,
    inactive: 80,
    disabled: 45,
    resigned: 20
};

const defaultDepartments: DataNode[] = [
  {
    key: '1',
    title: '腾讯科技 (深圳) 有限公司',
    children: [
      {
        key: '1-1',
        title: '平台与内容事业群 (PCG)',
        children: [
          { key: '1-1-1', title: '技术中台' },
          { key: '1-1-2', title: '内容业务线' },
        ],
      },
      {
        key: '1-2',
        title: '云与智慧产业事业群 (CSIG)',
        children: [
          { key: '1-2-1', title: '云产品部' },
          { key: '1-2-2', title: '智慧行业部' },
        ],
      },
    ],
  },
];

const defaultEmployees = Array.from({ length: 20 }).map((_, i) => ({
    id: `EMP-${1000 + i}`,
    key: `EMP-${1000 + i}`,
    avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${i}`,
    name: `员工 ${i + 1}`,
    mobile: `138${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}1234`,
    department: i % 2 === 0 ? '技术中台' : '云产品部',
    parentDepartment: i % 2 === 0 ? '平台与内容事业群 (PCG)' : '云与智慧产业事业群 (CSIG)',
    status: i % 10 === 0 ? 'disabled' : (i % 5 === 0 ? 'inactive' : 'active'),
    accountStatus: i % 10 === 0 ? '异常' : '正常',
    customerCount: Math.floor(Math.random() * 200),
}));

// --- Component ---

const Component = forwardRef<AxureHandle, AxureProps>((props, ref) => {
  const { data, onEvent } = props;
  const { token } = theme.useToken();
  
  // State
  const [searchValue, setSearchValue] = useState('');
  const [employeeSearch, setEmployeeSearch] = useState('');
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['1', '1-1', '1-2']);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // Modals
  const [isRestoreModalVisible, setIsRestoreModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [currentEmployee, setCurrentEmployee] = useState<any>(null);
  const [form] = Form.useForm();
  const [restoreForm] = Form.useForm();

  const handleMenuSelect = React.useCallback((key: string) => {
    const target = resolveMenuTarget(key);
    if (target) {
      window.location.href = target;
    }
  }, []);

  const stats = data?.stats || defaultStats;
  const departments = (data?.departments as DataNode[]) || defaultDepartments;
  const allEmployees = (data?.employees || defaultEmployees);

  // Helper to find node title by key
  const findNodeTitle = (key: React.Key, nodes: DataNode[]): string | null => {
      for (const node of nodes) {
          if (node.key === key) return node.title as string;
          if (node.children) {
              const res = findNodeTitle(key, node.children);
              if (res) return res;
          }
      }
      return null;
  };

  const selectedDepartmentName = useMemo(() => {
      if (selectedKeys.length === 0) return null;
      return findNodeTitle(selectedKeys[0], departments);
  }, [selectedKeys, departments]);

  // Filter Employees
  const filteredEmployees = useMemo(() => {
      return allEmployees.filter((emp: any) => {
          const matchesSearch = emp.name.includes(employeeSearch) || emp.mobile.includes(employeeSearch);
          // Simple mock filter: if department selected, match exact name
          // In real app, this might match ID or recursively match children
          const matchesDept = selectedDepartmentName ? emp.department === selectedDepartmentName : true;
          return matchesSearch && matchesDept;
      });
  }, [allEmployees, employeeSearch, selectedDepartmentName]);

  // Tree Search Logic
  const dataList: { key: React.Key; title: string; parentKey?: React.Key }[] = [];
  const generateList = (data: DataNode[], parentKey?: React.Key) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title: title as string, parentKey });
      if (node.children) {
        generateList(node.children, key);
      }
    }
  };
  generateList(departments);

  const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const onTreeSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, departments);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
      
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const treeLoop = (data: DataNode[]): DataNode[] =>
    data.map((item) => {
      const strTitle = item.title as string;
      const index = strTitle.indexOf(searchValue);
      const beforeStr = strTitle.substring(0, index);
      const afterStr = strTitle.slice(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: token.colorError }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{strTitle}</span>
        );
      if (item.children) {
        return { title, key: item.key, children: treeLoop(item.children) };
      }
      return { title, key: item.key };
    });

  // Table Actions
  const handleRestore = (record?: any) => {
      setCurrentEmployee(record);
      restoreForm.resetFields();
      setIsRestoreModalVisible(true);
  };

  const handleEdit = (record: any) => {
      setCurrentEmployee(record);
      form.setFieldsValue({
          department: record.department,
          customField1: '示例值',
      });
      setIsEditModalVisible(true);
  };

  const handleSyncCustomer = (record: any) => {
      Modal.confirm({
          title: '确认同步客户?',
          content: `即将同步员工 ${record.name} 的客户数据。`,
          onOk: () => {
              message.success('同步指令已下发');
              onEvent?.('onSyncCustomer', { id: record.id });
          }
      });
  };

  const columns: ColumnsType<any> = [
    {
        title: '员工',
        key: 'name',
        width: 200,
        render: (_, record) => (
            <Space>
                <Avatar src={record.avatar} />
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                    <Text strong>{record.name}</Text>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                        {record.mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
                    </Text>
                </div>
            </Space>
        ),
    },
    {
        title: '归属部门',
        key: 'department',
        render: (_, record) => (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
                <Text>{record.department}</Text>
                <Text type="secondary" style={{ fontSize: 12 }}>{record.parentDepartment}</Text>
            </div>
        )
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (status) => {
            const config = {
                active: { color: 'success', text: '已激活' },
                inactive: { color: 'warning', text: '未激活' },
                disabled: { color: 'error', text: '已禁用' },
                resigned: { color: 'default', text: '已离职' }
            }[status as string] || { color: 'default', text: '未知' };
            return <Tag color={config.color}>{config.text}</Tag>;
        }
    },
    {
        title: '账号状态',
        dataIndex: 'accountStatus',
        key: 'accountStatus',
    },
    {
        title: '客户数',
        dataIndex: 'customerCount',
        key: 'customerCount',
        sorter: (a, b) => a.customerCount - b.customerCount,
    },
    {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 220,
        render: (_, record) => (
            <Space size="small">
                <Button type="link" size="small" onClick={() => handleSyncCustomer(record)}>同步客户</Button>
                <Button type="link" size="small" onClick={() => handleRestore(record)}>赋权</Button>
                <Button type="link" size="small" onClick={() => handleEdit(record)}>编辑</Button>
            </Space>
        ),
    },
  ];

  useImperativeHandle(ref, () => ({
      eventList: [
          { name: 'onSyncCorp', desc: '同步企微组织' },
          { name: 'onSyncMembers', desc: '同步企微成员' },
          { name: 'onBatchRestore', desc: '批量赋权' },
          { name: 'onRestore', desc: '赋权' },
          { name: 'onEdit', desc: '编辑' },
          { name: 'onSyncCustomer', desc: '同步客户' },
      ],
      actionList: [{ name: 'refreshData', desc: '刷新数据' }],
      varList: [],
      configList: [{ type: 'input', attributeId: 'title', displayName: '页面标题', initialValue: '员工管理' }],
      dataList: []
  }));

  const StatsCard = ({ title, value, color, icon }: any) => (
      <Card bordered={false} bodyStyle={{ padding: 16 }}>
          <Statistic
            title={<Text type="secondary" style={{ fontSize: 13 }}>{title}</Text>}
            value={value}
            valueStyle={{ color, fontWeight: 'bold', fontSize: 20 }}
            prefix={icon}
          />
      </Card>
  );

  return (
    <Layout style={{ minHeight: '100vh' }} hasSider>
      <SideMenu
        title="企微运营"
        width={280}
        defaultSelectedKey="enterprise_employee"
        items={MENU_ITEMS}
        onMenuSelect={handleMenuSelect}
      />
      <Layout>
        <div style={{ padding: 24, background: '#f5f7fa', minHeight: '100vh', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Stats Section */}
        <Row gutter={[16, 16]}>
            <Col flex={1}><StatsCard title="企业员工数" value={stats.total} color="#1677ff" icon={<TeamOutlined />} /></Col>
            <Col flex={1}><StatsCard title="激活员工数" value={stats.active} color="#52c41a" icon={<CheckCircleOutlined />} /></Col>
            <Col flex={1}><StatsCard title="未激活员工数" value={stats.inactive} color="#faad14" icon={<SafetyCertificateOutlined />} /></Col>
            <Col flex={1}><StatsCard title="禁用员工数" value={stats.disabled} color="#ff4d4f" icon={<StopOutlined />} /></Col>
            <Col flex={1}><StatsCard title="退出企业数" value={stats.resigned} color="#8c8c8c" icon={<LogoutOutlined />} /></Col>
        </Row>

        {/* Main Content */}
        <Layout style={{ background: '#fff', padding: 0, borderRadius: 8, overflow: 'hidden', flex: 1 }}>
            <Sider width={280} theme="light" style={{ borderRight: '1px solid #f0f0f0' }}>
                <div style={{ padding: 16, borderBottom: '1px solid #f0f0f0' }}>
                    <Search 
                        placeholder="搜索部门" 
                        onChange={onTreeSearch}
                        allowClear
                    />
                </div>
                <div style={{ padding: '12px 0 12px 12px', height: 'calc(100% - 65px)', overflowY: 'auto' }}>
                    {departments.length > 0 ? (
                        <Tree
                            onExpand={(keys) => setExpandedKeys(keys)}
                            expandedKeys={expandedKeys}
                            autoExpandParent={autoExpandParent}
                            treeData={treeLoop(departments)}
                            onSelect={setSelectedKeys}
                            selectedKeys={selectedKeys}
                            blockNode
                        />
                    ) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                </div>
            </Sider>
            <Content style={{ padding: 24, display: 'flex', flexDirection: 'column', height: '100%' }}>
                {/* Toolbar */}
                <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                    <Space>
                        <Search 
                            placeholder="搜索姓名/手机号" 
                            style={{ width: 240 }} 
                            onChange={(e) => setEmployeeSearch(e.target.value)}
                            allowClear
                        />
                    </Space>
                    <Space>
                        <Button onClick={() => handleRestore()}>批量赋权</Button>
                        <Button icon={<DeploymentUnitOutlined />} onClick={() => onEvent?.('onSyncCorp', null)}>同步企微组织</Button>
                        <Button icon={<SyncOutlined />} onClick={() => onEvent?.('onSyncMembers', null)}>同步企微成员</Button>
                    </Space>
                </div>

                {/* Table */}
                <Table
                    rowSelection={{
                        selectedRowKeys,
                        onChange: setSelectedRowKeys,
                    }}
                    columns={columns}
                    dataSource={filteredEmployees}
                    pagination={{ pageSize: 10, showSizeChanger: true, showTotal: (total) => `共 ${total} 条` }}
                    scroll={{ x: 1000 }}
                    style={{ flex: 1 }}
                />
            </Content>
        </Layout>

        {/* Restore Modal */}
        <Modal
            title={currentEmployee ? "赋权" : "批量赋权"}
            open={isRestoreModalVisible}
            onOk={() => {
                setIsRestoreModalVisible(false);
                message.success('操作成功');
                onEvent?.(currentEmployee ? 'onRestore' : 'onBatchRestore', currentEmployee ? currentEmployee.id : selectedRowKeys);
            }}
            onCancel={() => setIsRestoreModalVisible(false)}
        >
            <Form form={restoreForm} layout="vertical">
                <Form.Item name="role" label="选择系统角色" rules={[{ required: true }]}>
                    <Select placeholder="请选择角色">
                        <Option value="admin">超级管理员</Option>
                        <Option value="manager">部门经理</Option>
                        <Option value="staff">普通员工</Option>
                    </Select>
                </Form.Item>
            </Form>
        </Modal>

        {/* Edit Modal */}
        <Modal
            title="编辑员工信息"
            open={isEditModalVisible}
            onOk={() => {
                setIsEditModalVisible(false);
                message.success('修改成功');
                onEvent?.('onEdit', { ...currentEmployee, ...form.getFieldsValue() });
            }}
            onCancel={() => setIsEditModalVisible(false)}
        >
            <Form form={form} layout="vertical">
                <Form.Item name="department" label="归属部门">
                    <Select>
                        <Option value="技术中台">技术中台</Option>
                        <Option value="云产品部">云产品部</Option>
                    </Select>
                </Form.Item>
                <Divider dashed orientation={"left" as any}>自定义字段</Divider>
                <Form.Item name="customField1" label="自定义字段 1 (参考腾讯文档)">
                    <Input />
                </Form.Item>
                <Form.Item name="customField2" label="自定义字段 2">
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
        </div>
      </Layout>
    </Layout>
  );
});

export default Component;
