import { useState, useEffect } from "react";
import {
    Table,
    Button,
    TextInput,
    Select,
    Loader,
    Center,
    Text,
    Grid,
} from "@mantine/core";
import { EXTERNAL_API } from "../config/api";
import PaginationControl from "../components/PaginationControl";
import NodeStatus from "../components/NodeStatus";
import NodeModal from "../components/NodeModal";
import NodeDetailDrawer from "../components/NodeDetailDrawer";
import { apiRequest } from "../config/request";

export default function NodePage() {
    const [nodes, setNodes] = useState([]);
    const [totalCount, setTotalCount] = useState(0);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [modalOpen, setModalOpen] = useState(false);
    const [editNode, setEditNode] = useState(null);
    const [loading, setLoading] = useState(false);

    // 查询条件
    const [searchName, setSearchName] = useState("");
    const [searchStatus, setSearchStatus] = useState("");

    // 详情相关
    const [selectedNode, setSelectedNode] = useState(null);
    const [detailLoading, setDetailLoading] = useState(false);
    const [drawerOpen, setDrawerOpen] = useState(false);

    // 获取节点数据（支持查询和分页）
    const fetchNodes = async (params = {}) => {
        setLoading(true);
        try {
            // 构建查询参数
            const query = new URLSearchParams({
                page: params.page || page,
                pageSize: params.pageSize || pageSize,
                name: params.name !== undefined ? params.name : searchName,
                status: params.status !== undefined ? params.status : searchStatus,
            }).toString();

            const result = await apiRequest(`${EXTERNAL_API.MASTER_NODES}?${query}`);
            setNodes(result.data);
            setTotalCount(result.total || 0);
        } finally {
            setLoading(false);
        }
    };

    // 获取节点详情
    const fetchNodeDetail = async (id) => {
        setDetailLoading(true);
        setDrawerOpen(true);
        try {
            const result = await apiRequest(`${EXTERNAL_API.MASTER_NODES}/${id}`);
            setSelectedNode(result);
        } finally {
            setDetailLoading(false);
        }
    };
    useEffect(() => {
        fetchNodes();
    }, []);

    // 搜索
    const handleSearch = () => {
        setPage(1); // 搜索时分页重置
        fetchNodes({ page: 1, name: searchName, status: searchStatus });
    };

    return (
        <Grid gutter="lg">
            {/* 左侧：表格 */}
            <Grid.Col span={selectedNode ? 8 : 12}>
                {/* 顶部操作区 */}
                <div
                    style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        marginBottom: 16,
                    }}
                >
                    {/* 搜索区 */}
                    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                        <TextInput
                            placeholder="搜索节点名称"
                            value={searchName}
                            onChange={(e) => setSearchName(e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === "Enter") handleSearch();
                            }}
                            style={{ width: 200 }}
                        />
                        <Select
                            data={[
                                { value: "", label: "全部状态" },
                                { value: "healthy", label: "Healthy" },
                                { value: "warning", label: "Warning" },
                                { value: "error", label: "Error" },
                            ]}
                            value={searchStatus}
                            onChange={setSearchStatus}
                            placeholder="状态"
                            style={{ width: 120 }}
                        />
                        <Button onClick={handleSearch}>搜索</Button>
                    </div>

                    {/* 操作按钮 */}
                    <div style={{ display: "flex", gap: 8 }}>
                        <Button
                            onClick={() => fetchNodes({ name: searchName, status: searchStatus })}
                            variant="outline"
                        >
                            刷新列表
                        </Button>
                    </div>
                </div>

                {loading ? (
                    <Center h={200}>
                        <Loader size="lg" />
                    </Center>
                ) : (
                    <>
                        <Table striped highlightOnHover withTableBorder>
                            <Table.Thead>
                                <Table.Tr>
                                    <Table.Th>ID</Table.Th>
                                    <Table.Th>名称</Table.Th>
                                    <Table.Th>状态</Table.Th>
                                    <Table.Th>类型</Table.Th>
                                    <Table.Th>版本</Table.Th>
                                    <Table.Th>操作</Table.Th>
                                </Table.Tr>
                            </Table.Thead>
                            <Table.Tbody>
                                {nodes.map((node) => (
                                    <Table.Tr key={node.id}>
                                        <Table.Td>{node.id}</Table.Td>
                                        <Table.Td>{node.name}</Table.Td>
                                        <Table.Td>
                                            <NodeStatus status={node.status} />
                                        </Table.Td>
                                        <Table.Td>{node.type}</Table.Td>
                                        <Table.Td>{node.version}</Table.Td>
                                        <Table.Td>
                                            <Button
                                                size="xs"
                                                variant="light"
                                                onClick={() => fetchNodeDetail(node.id)}
                                            >
                                                查看详情
                                            </Button>
                                        </Table.Td>
                                    </Table.Tr>
                                ))}
                            </Table.Tbody>
                        </Table>


                        <PaginationControl
                            totalItems={totalCount}
                            page={page}
                            pageSize={pageSize}
                            onPageChange={(p) => {
                                setPage(p);
                                fetchNodes({ page: p });
                            }}
                            onPageSizeChange={(size) => {
                                setPageSize(size);
                                setPage(1);
                                fetchNodes({ page: 1, pageSize: size });
                            }}
                        />
                    </>
                )}
            </Grid.Col>

            {/* 节点详情 Drawer */}
            <NodeDetailDrawer
                opened={drawerOpen}
                onClose={() => setDrawerOpen(false)}
                nodeId={selectedNode}
            />
        </Grid>
    );
}
