/**
 * 设备管理页
 * - 左侧：组织架构树（OrganizationTree 组件）
 * - 右侧：柜子卡片网格（CabinetGrid 组件）
 * - 右键菜单：添加组织/项目、编辑、删除
 * - 批量添加柜子弹窗（AddCabinetModal 组件）
 */
import { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Layout,
  Typography,
  Modal,
  Button,
  Form,
  Input,
  Dropdown,
  Menu,
  Message,
} from '@arco-design/web-react';
import {
  IconPlus,
  IconDelete,
  IconEdit,
} from '@arco-design/web-react/icon';
import {
  treeApi,
  orgApi,
  projectApi,
  cabinetApi,
  type TreeNode,
  type Cabinet,
  type Organization,
} from '@/api/devices';

import OrganizationTree, {
  buildTreeData,
  collectCabinets,
  findOrgInTree,
  type NodeType,
  type TreeInternalNode,
} from './OrganizationTree';
import CabinetGrid from './CabinetGrid';
import AddCabinetModal from './AddCabinetModal';

const Content = Layout.Content;

export default function Devices() {
  const navigate = useNavigate();
  const [treeData, setTreeData] = useState<TreeInternalNode[]>([]);
  const [rawTree, setRawTree] = useState<TreeNode[]>([]);
  const [cabinets, setCabinets] = useState<Cabinet[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [selectedType, setSelectedType] = useState<NodeType>('all');
  const [selectedId, setSelectedId] = useState(0);

  // 弹窗状态
  const [orgModalVisible, setOrgModalVisible] = useState(false);
  const [projectModalVisible, setProjectModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editValue, setEditValue] = useState('');
  const [editingId, setEditingId] = useState(0);
  const [editingType, setEditingType] = useState<NodeType>('organization');

  // 添加柜子弹窗
  const [cabinetModalVisible, setCabinetModalVisible] = useState(false);
  const [orgList, setOrgList] = useState<Organization[]>([]);

  // 右键菜单
  const [contextNode, setContextNode] = useState<{ type: NodeType; id: number } | null>(null);
  const [contextVisible, setContextVisible] = useState(false);
  const [contextPos, setContextPos] = useState({ x: 0, y: 0 });

  // -------- 数据加载 --------

  const loadTree = useCallback(async () => {
    try {
      const res = await treeApi.get();
      const data = (res as unknown as TreeNode[]) || [];
      setRawTree(data);
      setTreeData(buildTreeData(data));
    } catch {
      Message.error('加载组织树失败');
    }
  }, []);

  const loadCabinets = useCallback(async (type: NodeType, id: number) => {
    if (type === 'cabinet') {
      navigate(`/devices/cabinet/${id}`);
      return;
    }
    setLoading(true);
    try {
      if (type === 'all') {
        setCabinets(collectCabinets(rawTree));
      } else if (type === 'organization') {
        const org = findOrgInTree(rawTree, id);
        setCabinets(org?.children ? collectCabinets(org.children) : []);
      } else if (type === 'project') {
        const res = await cabinetApi.list(id);
        setCabinets((res as unknown as Cabinet[]) || []);
      }
    } catch {
      Message.error('加载柜子列表失败');
    } finally {
      setLoading(false);
    }
  }, [rawTree, navigate]);

  useEffect(() => {
    loadTree().then(() => setLoading(false));
  }, [loadTree]);

  useEffect(() => {
    if (selectedType) {
      loadCabinets(selectedType, selectedId);
    }
  }, [selectedType, selectedId, loadCabinets]);

  const handleTreeSelect = useCallback((keys: string[]) => {
    const key = keys[0];
    if (!key || key === 'all') {
      setSelectedKeys(keys);
      setSelectedType('all');
      setSelectedId(0);
      return;
    }
    setSelectedKeys(keys);
    if (key.startsWith('org-')) {
      setSelectedType('organization');
      setSelectedId(Number(key.replace('org-', '')));
    } else if (key.startsWith('proj-')) {
      setSelectedType('project');
      setSelectedId(Number(key.replace('proj-', '')));
    } else if (key.startsWith('cab-')) {
      setSelectedType('cabinet');
      setSelectedId(Number(key.replace('cab-', '')));
    }
  }, []);

  // -------- 组织/项目 CRUD --------

  const handleAddOrg = () => {
    setEditTitle('添加组织');
    setEditValue('');
    setEditingType('organization');
    setOrgModalVisible(true);
  };

  const handleAddProject = (orgId: number) => {
    setEditTitle('添加项目');
    setEditValue('');
    setEditingType('project');
    setEditingId(orgId);
    setProjectModalVisible(true);
  };

  const handleEdit = (type: NodeType, id: number, currentName: string) => {
    setEditTitle(type === 'organization' ? '编辑组织' : '编辑项目');
    setEditValue(currentName);
    setEditingType(type);
    setEditingId(id);
    setEditModalVisible(true);
  };

  const handleDelete = (type: NodeType, id: number) => {
    const label = type === 'organization' ? '组织' : '项目';
    Modal.confirm({
      title: `确认删除${label}`,
      content: `确定要删除此${label}吗？该操作不可撤销。`,
      okButtonProps: { status: 'danger' },
      onOk: async () => {
        try {
          if (type === 'organization') {
            await orgApi.delete(id);
          } else {
            await projectApi.delete(id);
          }
          Message.success(`删除${label}成功`);
          await loadTree();
          setSelectedKeys([]);
          setCabinets([]);
        } catch (e: unknown) {
          const msg = e instanceof Error ? e.message : `删除${label}失败`;
          Message.error(msg);
        }
      },
    });
  };

  const handleCreateOrg = async () => {
    if (!editValue.trim()) { Message.warning('请输入组织名称'); return; }
    try {
      await orgApi.create({ name: editValue.trim() });
      Message.success('创建组织成功');
      setOrgModalVisible(false);
      await loadTree();
    } catch (e: unknown) {
      Message.error(e instanceof Error ? e.message : '创建组织失败');
    }
  };

  const handleCreateProject = async () => {
    if (!editValue.trim()) { Message.warning('请输入项目名称'); return; }
    try {
      await projectApi.create(editingId, { name: editValue.trim() });
      Message.success('创建项目成功');
      setProjectModalVisible(false);
      await loadTree();
    } catch (e: unknown) {
      Message.error(e instanceof Error ? e.message : '创建项目失败');
    }
  };

  const handleEditSave = async () => {
    if (!editValue.trim()) { Message.warning('请输入名称'); return; }
    try {
      if (editingType === 'organization') {
        await orgApi.update(editingId, { name: editValue.trim() });
      } else {
        await projectApi.update(editingId, { name: editValue.trim() });
      }
      Message.success('保存成功');
      setEditModalVisible(false);
      await loadTree();
    } catch (e: unknown) {
      Message.error(e instanceof Error ? e.message : '保存失败');
    }
  };

  // -------- 右键菜单 --------

  const handleRightClick = (ev: React.MouseEvent, nodeType: NodeType, nodeId: number) => {
    if (nodeType === 'cabinet') return;
    ev.preventDefault();
    ev.stopPropagation();
    setContextNode({ type: nodeType, id: nodeId });
    setContextPos({ x: ev.clientX, y: ev.clientY });
    setContextVisible(true);
  };

  const handleContextMenuClick = (menuKey: string) => {
    setContextVisible(false);
    if (!contextNode) return;
    switch (menuKey) {
      case 'add-org': handleAddOrg(); break;
      case 'add-project': handleAddProject(contextNode.id); break;
      case 'edit': handleEdit(contextNode.type, contextNode.id, ''); break;
      case 'delete': handleDelete(contextNode.type, contextNode.id); break;
    }
  };

  // -------- 添加柜子 --------

  const openCabinetModal = async () => {
    try {
      const res = await orgApi.list();
      setOrgList((res as unknown as Organization[]) || []);
    } catch {
      Message.error('加载组织列表失败');
    }
    setCabinetModalVisible(true);
  };

  const contextMenu = (
    <Menu onClickMenuItem={handleContextMenuClick}>
      {(!contextNode || contextNode.type === 'all') && (
        <Menu.Item key="add-org"><IconPlus style={{ marginRight: 8 }} />添加组织</Menu.Item>
      )}
      {contextNode?.type === 'organization' && (
        <>
          <Menu.Item key="add-project"><IconPlus style={{ marginRight: 8 }} />添加项目</Menu.Item>
          <Menu.Item key="edit"><IconEdit style={{ marginRight: 8 }} />编辑</Menu.Item>
          <Menu.Item key="delete"><IconDelete style={{ marginRight: 8 }} />删除</Menu.Item>
        </>
      )}
      {contextNode?.type === 'project' && (
        <>
          <Menu.Item key="edit"><IconEdit style={{ marginRight: 8 }} />编辑</Menu.Item>
          <Menu.Item key="delete"><IconDelete style={{ marginRight: 8 }} />删除</Menu.Item>
        </>
      )}
    </Menu>
  );

  return (
    <Layout style={{ height: '100%', background: 'transparent' }}>
      <OrganizationTree
        treeData={treeData}
        loading={loading}
        selectedKeys={selectedKeys}
        onSelect={handleTreeSelect}
        onReload={loadTree}
        onRightClick={handleRightClick}
      />

      <Content style={{ padding: '0 0 0 16px', overflow: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <Typography.Title heading={5} style={{ margin: 0 }}>
            设备列表 ({cabinets.length})
          </Typography.Title>
          <Button type="primary" icon={<IconPlus />} onClick={openCabinetModal}>
            添加柜子
          </Button>
        </div>
        <CabinetGrid cabinets={cabinets} loading={loading} />
      </Content>

      {/* 右键菜单 */}
      <Dropdown
        popupVisible={contextVisible}
        droplist={contextMenu}
        position="bl"
      >
        <div
          style={{ position: 'fixed', left: contextPos.x, top: contextPos.y, width: 0, height: 0 }}
          onClick={() => setContextVisible(false)}
        />
      </Dropdown>

      {/* 添加组织弹窗 */}
      <Modal title="添加组织" visible={orgModalVisible} onCancel={() => setOrgModalVisible(false)} onOk={handleCreateOrg} okText="确定" cancelText="取消">
        <Form layout="vertical">
          <Form.Item label="组织名称" required>
            <Input placeholder="请输入组织名称" value={editValue} onChange={setEditValue} onPressEnter={handleCreateOrg} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加项目弹窗 */}
      <Modal title="添加项目" visible={projectModalVisible} onCancel={() => setProjectModalVisible(false)} onOk={handleCreateProject} okText="确定" cancelText="取消">
        <Form layout="vertical">
          <Form.Item label="项目名称" required>
            <Input placeholder="请输入项目名称" value={editValue} onChange={setEditValue} onPressEnter={handleCreateProject} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑弹窗 */}
      <Modal title={editTitle} visible={editModalVisible} onCancel={() => setEditModalVisible(false)} onOk={handleEditSave} okText="保存" cancelText="取消">
        <Form layout="vertical">
          <Form.Item label="名称" required>
            <Input placeholder="请输入名称" value={editValue} onChange={setEditValue} onPressEnter={handleEditSave} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加柜子弹窗 */}
      <AddCabinetModal
        visible={cabinetModalVisible}
        orgList={orgList}
        onCancel={() => setCabinetModalVisible(false)}
        onSuccess={async () => { setCabinetModalVisible(false); await loadTree(); }}
      />
    </Layout>
  );
}
