import { useState, useEffect } from "react";
import { Modal, TextInput, Select, Button } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { EXTERNAL_API } from "../config/api";
import { statusOptions } from "../config/status";
import { apiRequest } from "../config/request";

export default function NodeModal({ opened, onClose, node, onSaved }) {
    const [form, setForm] = useState({ name: "", status: "healthy", load: 0 });
    const [loading, setLoading] = useState(false);
    const [errors, setErrors] = useState({ name: "", load: "" });

    // 初始化表单
    useEffect(() => {
        setForm(node ? { ...node } : { name: "", status: "healthy", load: 0 });
        setErrors({ name: "", load: "" });
    }, [node]);

    // 实时校验
    const validateField = (field, value) => {
        switch (field) {
            case "name":
                setErrors((prev) => ({
                    ...prev,
                    name: value.trim() ? "" : "名称不能为空",
                }));
                break;
            case "load":
                const loadNum = Number(value);
                setErrors((prev) => ({
                    ...prev,
                    load:
                        isNaN(loadNum) || loadNum < 0 || loadNum > 100
                            ? "负载必须是 0~100 的数字"
                            : "",
                }));
                break;
            default:
                break;
        }
    };

    const handleSave = async () => {
        const name = form.name.trim();
        const load = Number(form.load);
        let hasError = false;

        if (!name) {
            setErrors((prev) => ({ ...prev, name: "名称不能为空" }));
            notifications.show({
                title: "校验失败",
                message: "名称不能为空 ❌",
                color: "red",
            });
            hasError = true;
        }
        if (isNaN(load) || load < 0 || load > 100) {
            setErrors((prev) => ({ ...prev, load: "负载必须是 0~100 的数字" }));
            notifications.show({
                title: "校验失败",
                message: "负载必须是 0~100 的数字 ❌",
                color: "red",
            });
            hasError = true;
        }
        if (hasError) return;

        const method = node ? "PUT" : "POST";
        const url = node ? `${EXTERNAL_API.MASTER_NODES}/${node.id}` : EXTERNAL_API.MASTER_NODES;

        setLoading(true);
        try {
            await apiRequest(url, {
                method,
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ ...form, name, load }),
            });
            notifications.show({
                title: "成功",
                message: node ? "节点已更新 ✅" : "节点已新增 ✅",
                color: "green",
                autoClose: 3000,
            });

            setTimeout(() => {
                onClose();
                onSaved();
            }, 3000);
        } catch (err) {
            notifications.show({
                title: "错误",
                message: `操作失败: ${err.message || "未知错误"}`,
                color: "red",
            });
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={node ? "编辑节点" : "新增节点"}
        >
            <TextInput
                label="名称"
                value={form.name}
                onChange={(e) => {
                    const value = e.target.value;
                    setForm((prev) => ({ ...prev, name: value }));
                    validateField("name", value);
                }}
                mb="sm"
                error={errors.name}
                required
            />
            <Select
                label="状态"
                data={statusOptions}
                value={form.status}
                onChange={(val) => setForm((prev) => ({ ...prev, status: val }))}
                mb="sm"
            />
            <TextInput
                label="负载"
                type="number"
                value={form.load}
                onChange={(e) => {
                    const value = e.target.value;
                    setForm((prev) => ({ ...prev, load: value }));
                    validateField("load", value);
                }}
                mb="sm"
                error={errors.load}
            />
            <Button mt="md" onClick={handleSave} loading={loading}>
                保存
            </Button>
        </Modal>
    );
}
