import React, { useEffect, useState, useCallback } from 'react';
import {
  Tree,
  Card,
  Button,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Table,
  Row,
  Col,
  Popconfirm,
  Space,
  message,
  Tag,
  Descriptions,
  Empty,
  Spin,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';

interface DepartmentItem {
  id: number;
  name: string;
  parentId: number | null;
  type: string;
  sortOrder: number;
  status: string;
  children?: DepartmentItem[];
}

interface UserInfo {
  id: number;
  username: string;
  name: string;
  isActive: boolean;
}

interface DeptMember {
  id: number;
  userId: number;
  departmentId: number;
  isDefault: boolean;
  user: UserInfo;
}

function departmentToTreeNode(dept: DepartmentItem): DataNode {
  return {
    key: String(dept.id),
    title: dept.name,
    children: dept.children?.map(departmentToTreeNode),
  };
}

const TYPE_LABELS: Record<string, string> = {
  campus: '校区',
  department: '部门',
};

const TYPE_COLORS: Record<string, string> = {
  campus: 'blue',
  department: 'green',
};

const DepartmentsPage: React.FC = () => {
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [flatDepts, setFlatDepts] = useState<DepartmentItem[]>([]);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [selectedDept, setSelectedDept] = useState<DepartmentItem | null>(null);
  const [members, setMembers] = useState<DeptMember[]>([]);
  const [membersLoading, setMembersLoading] = useState(false);
  const [treeLoading, setTreeLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<DepartmentItem | null>(null);
  const [form] = Form.useForm();

  const fetchTree = useCallback(async () => {
    setTreeLoading(true);
    try {
      const data = await api.get('/departments/tree') as unknown as DepartmentItem[];
      const flat = await api.get('/departments') as unknown as DepartmentItem[];
      setFlatDepts(flat);
      setTreeData(data.map(departmentToTreeNode));
    } catch {
      message.error('加载部门树失败');
    } finally {
      setTreeLoading(false);
    }
  }, []);

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

  const fetchDetail = useCallback(async (id: number) => {
    try {
      const dept = await api.get(`/departments/${id}`) as unknown as DepartmentItem;
      setSelectedDept(dept);
      setMembersLoading(true);
      const users = await api.get(`/departments/${id}/users`) as unknown as DeptMember[];
      setMembers(users);
    } catch {
      message.error('加载部门详情失败');
    } finally {
      setMembersLoading(false);
    }
  }, []);

  const handleSelect = useCallback(
    (keys: React.Key[]) => {
      if (keys.length === 0) {
        setSelectedId(null);
        setSelectedDept(null);
        setMembers([]);
        return;
      }
      const id = String(keys[0]);
      setSelectedId(id);
      fetchDetail(Number(id));
    },
    [fetchDetail],
  );

  const handleAdd = useCallback(() => {
    setEditing(null);
    form.resetFields();
    if (selectedId) {
      form.setFieldsValue({ parentId: Number(selectedId) });
    }
    setModalOpen(true);
  }, [selectedId, form]);

  const handleAddChild = useCallback(() => {
    if (!selectedDept) return;
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ parentId: selectedDept.id });
    setModalOpen(true);
  }, [selectedDept, form]);

  const handleEdit = useCallback(() => {
    if (!selectedDept) return;
    setEditing(selectedDept);
    form.setFieldsValue({
      name: selectedDept.name,
      parentId: selectedDept.parentId,
      type: selectedDept.type,
      sortOrder: selectedDept.sortOrder,
    });
    setModalOpen(true);
  }, [selectedDept, form]);

  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        name: values.name,
        parentId: values.parentId || null,
        type: values.type || 'department',
        sortOrder: values.sortOrder ?? 0,
      };
      if (editing) {
        await api.put(`/departments/${editing.id}`, payload);
        message.success('更新成功');
      } else {
        await api.post('/departments', payload);
        message.success('创建成功');
      }
      setModalOpen(false);
      await fetchTree();
      if (editing && selectedId) {
        fetchDetail(editing.id);
      }
    } catch {
      // form validation error: do nothing
    }
  }, [editing, fetchTree, fetchDetail, selectedId, form]);

  const handleDelete = useCallback(async () => {
    if (!selectedDept) return;
    try {
      await api.delete(`/departments/${selectedDept.id}`);
      message.success('删除成功');
      setSelectedId(null);
      setSelectedDept(null);
      setMembers([]);
      await fetchTree();
    } catch (err: unknown) {
      const msg =
        err && typeof err === 'object' && 'message' in err
          ? (err as { message: string }).message
          : '删除失败';
      message.error(msg);
    }
  }, [selectedDept, fetchTree]);

  const memberColumns = [
    { title: 'ID', dataIndex: 'userId', key: 'userId', width: 60 },
    { title: '用户名', dataIndex: ['user', 'username'], key: 'username' },
    { title: '姓名', dataIndex: ['user', 'name'], key: 'name' },
    {
      title: '默认部门',
      dataIndex: 'isDefault',
      key: 'isDefault',
      width: 80,
      render: (v: boolean) => (v ? <Tag color="blue">是</Tag> : null),
    },
  ];

  return (
    <div>
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <h2 style={{ margin: 0 }}>组织架构管理</h2>
        <Space>
          <Button onClick={fetchTree} loading={treeLoading}>
            刷新
          </Button>
          <PermissionButton
            permission="department:create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </PermissionButton>
        </Space>
      </div>

      <Row gutter={16}>
        <Col xs={24} sm={24} md={8}>
          <Card
            title="部门结构"
            size="small"
            style={{ height: 'calc(100vh - 220px)', overflow: 'auto' }}
          >
            {treeLoading ? (
              <Spin style={{ display: 'block', margin: '40px auto' }} />
            ) : (
              <Tree
                treeData={treeData}
                showLine={{ showLeafIcon: false }}
                selectedKeys={selectedId ? [selectedId] : []}
                onSelect={handleSelect}
                blockNode
              />
            )}
          </Card>
        </Col>

        <Col xs={24} sm={24} md={16}>
          {selectedDept ? (
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <Card
                title={
                  <Space>
                    <span>{selectedDept.name}</span>
                    <Tag color={TYPE_COLORS[selectedDept.type] || 'default'}>
                      {TYPE_LABELS[selectedDept.type] || selectedDept.type}
                    </Tag>
                  </Space>
                }
                extra={
                  <Space>
                    <PermissionButton
                      permission="department:update"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={handleEdit}
                    >
                      编辑
                    </PermissionButton>
                    <PermissionButton
                      permission="department:create"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={handleAddChild}
                    >
                      新增子部门
                    </PermissionButton>
                    <Popconfirm
                      title="确定删除该部门？"
                      description={selectedDept.children && selectedDept.children.length > 0
                        ? '该部门下存在子部门，可能无法删除'
                        : undefined}
                      onConfirm={handleDelete}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        disabled={
                          selectedDept.children && selectedDept.children.length > 0
                        }
                      >
                        删除
                      </Button>
                    </Popconfirm>
                  </Space>
                }
              >
                <Descriptions column={2} size="small" bordered>
                  <Descriptions.Item label="ID">{selectedDept.id}</Descriptions.Item>
                  <Descriptions.Item label="类型">
                    <Tag color={TYPE_COLORS[selectedDept.type] || 'default'}>
                      {TYPE_LABELS[selectedDept.type] || selectedDept.type}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="排序">
                    {selectedDept.sortOrder}
                  </Descriptions.Item>
                  <Descriptions.Item label="上级部门 ID">
                    {selectedDept.parentId ?? '无（顶级）'}
                  </Descriptions.Item>
                  <Descriptions.Item label="状态">
                    <Tag color={selectedDept.status === 'active' ? 'green' : 'red'}>
                      {selectedDept.status}
                    </Tag>
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Card title="部门成员" size="small">
                <Table
                  columns={memberColumns}
                  dataSource={members}
                  rowKey="id"
                  loading={membersLoading}
                  pagination={false}
                  size="small"
                  scroll={{ x: 'max-content' }}
                  locale={{ emptyText: '暂无成员' }}
                />
              </Card>
            </Space>
          ) : (
            <Card
              size="small"
              style={{ height: 'calc(100vh - 220px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            >
              <Empty description="请在左侧选择一个部门" />
            </Card>
          )}
        </Col>
      </Row>

      <Modal
        title={editing ? '编辑部门' : '新增部门'}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={() => setModalOpen(false)}
        destroyOnHidden
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input placeholder="例如：数学教研组" />
          </Form.Item>

          <Form.Item name="parentId" label="上级部门">
            <Select
              allowClear
              placeholder="不选则为顶级部门"
              options={flatDepts.map((d) => ({
                value: d.id,
                label: d.name,
                disabled: editing ? d.id === editing.id : false,
              }))}
            />
          </Form.Item>

          <Form.Item name="type" label="类型" initialValue="department">
            <Select
              options={[
                { value: 'campus', label: '校区' },
                { value: 'department', label: '部门' },
              ]}
            />
          </Form.Item>

          <Form.Item name="sortOrder" label="排序序号" initialValue={0}>
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentsPage;
