"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FleetOptimizer = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const fi_1 = require("react-icons/fi");
const client_1 = require("@apollo/client");
const queries_js_1 = require("../../graphql/queries.js");
const mutations_js_1 = require("../../graphql/mutations.js");
const MetricChart_js_1 = require("../charts/MetricChart.js");
const formatters_js_1 = require("../../utils/formatters.js");
const FleetOptimizer = ({ fleetId, refreshInterval = 60000, }) => {
    const toast = (0, react_2.useToast)();
    const cardBg = (0, react_2.useColorModeValue)('white', 'gray.800');
    const borderColor = (0, react_2.useColorModeValue)('gray.200', 'gray.600');
    const [autoScaling, setAutoScaling] = (0, react_1.useState)(true);
    const [optimizationStrategy, setOptimizationStrategy] = (0, react_1.useState)('balanced');
    // Query optimization metrics
    const { data, loading, error } = (0, client_1.useQuery)(queries_js_1.GET_FLEET_OPTIMIZATION_METRICS, {
        variables: { fleetId },
        pollInterval: refreshInterval,
    });
    // Mutations for optimization actions
    const [optimizeResources] = (0, client_1.useMutation)(mutations_js_1.OPTIMIZE_FLEET_RESOURCES);
    const [updateScalingPolicy] = (0, client_1.useMutation)(mutations_js_1.UPDATE_FLEET_SCALING_POLICY);
    const metrics = data?.fleetOptimization;
    const handleOptimize = async () => {
        try {
            await optimizeResources({
                variables: {
                    fleetId,
                    strategy: optimizationStrategy,
                },
            });
            toast({
                title: 'Optimization Started',
                description: 'Fleet resources are being optimized based on the selected strategy.',
                status: 'success',
                duration: 5000,
            });
        }
        catch (error) {
            toast({
                title: 'Optimization Failed',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
        }
    };
    const handleAutoScalingChange = async (enabled) => {
        try {
            await updateScalingPolicy({
                variables: {
                    fleetId,
                    policy: {
                        enabled,
                        strategy: optimizationStrategy,
                    },
                },
            });
            setAutoScaling(enabled);
            toast({
                title: `Auto-scaling ${enabled ? 'Enabled' : 'Disabled'}`,
                status: 'success',
                duration: 3000,
            });
        }
        catch (error) {
            toast({
                title: 'Failed to Update Auto-scaling',
                description: error.message,
                status: 'error',
                duration: 5000,
            });
        }
    };
    if (loading) {
        return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, children: (0, jsx_runtime_1.jsx)(react_2.Progress, { size: "xs", isIndeterminate: true }) }));
    }
    if (error) {
        return ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, color: "red.500", children: ["Error loading optimization metrics: ", error.message] }));
    }
    if (!metrics) {
        return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, children: (0, jsx_runtime_1.jsx)(react_2.Text, { children: "No optimization data available" }) }));
    }
    return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 6, align: "stretch", children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 6, wrap: "wrap", children: [(0, jsx_runtime_1.jsxs)(react_2.FormControl, { display: "flex", alignItems: "center", children: [(0, jsx_runtime_1.jsx)(react_2.FormLabel, { htmlFor: "auto-scaling", mb: "0", children: "Auto-scaling" }), (0, jsx_runtime_1.jsx)(react_2.Switch, { id: "auto-scaling", isChecked: autoScaling, onChange: (e) => handleAutoScalingChange(e.target.checked) })] }), (0, jsx_runtime_1.jsx)(react_2.FormControl, { maxW: "200px", children: (0, jsx_runtime_1.jsxs)(react_2.Select, { value: optimizationStrategy, onChange: (e) => setOptimizationStrategy(e.target.value), children: [(0, jsx_runtime_1.jsx)("option", { value: "balanced", children: "Balanced" }), (0, jsx_runtime_1.jsx)("option", { value: "cost", children: "Cost-Optimized" }), (0, jsx_runtime_1.jsx)("option", { value: "performance", children: "Performance-Optimized" })] }) }), (0, jsx_runtime_1.jsx)(react_2.Button, { leftIcon: (0, jsx_runtime_1.jsx)(react_2.Icon, { as: fi_1.FiZap }), colorScheme: "blue", onClick: handleOptimize, children: "Optimize Now" })] }), (0, jsx_runtime_1.jsxs)(react_2.Grid, { templateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Cost Efficiency" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, formatters_js_1.formatPercentage)(metrics.costEfficiency) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: metrics.costEfficiency >= 85 ? 'increase' : 'decrease' }), "vs. Target"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Resource Utilization" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, formatters_js_1.formatPercentage)(metrics.resourceUtilization) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: metrics.resourceUtilization >= 70 ? 'increase' : 'decrease' }), "Optimal Range: 70-85%"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Scaling Efficiency" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, formatters_js_1.formatPercentage)(metrics.scalingEfficiency) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: metrics.scalingEfficiency >= 90 ? 'increase' : 'decrease' }), "Scale Events Success Rate"] })] })] }), (0, jsx_runtime_1.jsxs)(react_2.Grid, { templateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 6, children: [(0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "md", fontWeight: "bold", children: "Cost per Request Trend" }), (0, jsx_runtime_1.jsx)(MetricChart_js_1.MetricChart, { data: metrics.historicalMetrics.map((m) => ({
                                            timestamp: m.timestamp,
                                            value: m.costPerRequest,
                                        })), yAxisLabel: "$/request", height: 200, tooltipFormatter: (value) => (0, formatters_js_1.formatCurrency)(value, 'USD', 4) })] }) }), (0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "md", fontWeight: "bold", children: "Resource Utilization Trend" }), (0, jsx_runtime_1.jsx)(MetricChart_js_1.MetricChart, { data: metrics.historicalMetrics.map((m) => ({
                                            timestamp: m.timestamp,
                                            value: m.resourceUtilization,
                                        })), yAxisLabel: "Utilization %", height: 200, tooltipFormatter: (value) => (0, formatters_js_1.formatPercentage)(value) })] }) })] }), (0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, bg: cardBg, borderRadius: "lg", borderWidth: "1px", borderColor: borderColor, children: (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "md", fontWeight: "bold", children: "Optimization Recommendations" }), metrics.recommendations.map((rec) => ((0, jsx_runtime_1.jsxs)(react_2.HStack, { p: 3, bg: (0, react_2.useColorModeValue)('gray.50', 'gray.700'), borderRadius: "md", spacing: 4, children: [(0, jsx_runtime_1.jsx)(react_2.Icon, { as: rec.type === 'cost'
                                            ? fi_1.FiDollarSign
                                            : rec.type === 'performance'
                                                ? fi_1.FiZap
                                                : fi_1.FiServer, color: rec.priority === 'high'
                                            ? 'red.500'
                                            : rec.priority === 'medium'
                                                ? 'yellow.500'
                                                : 'blue.500' }), (0, jsx_runtime_1.jsxs)(react_2.VStack, { align: "start", spacing: 1, flex: 1, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "sm", children: rec.description }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 4, children: [rec.potentialSavings && ((0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "xs", color: "green.500", children: ["Potential Savings: ", (0, formatters_js_1.formatCurrency)(rec.potentialSavings)] })), (0, jsx_runtime_1.jsx)(react_2.Badge, { size: "sm", colorScheme: rec.implementationComplexity === 'easy'
                                                            ? 'green'
                                                            : rec.implementationComplexity === 'medium'
                                                                ? 'yellow'
                                                                : 'red', children: rec.implementationComplexity })] })] })] }, rec.id)))] }) })] }) }));
};
exports.FleetOptimizer = FleetOptimizer;
exports.default = exports.FleetOptimizer;
//# sourceMappingURL=FleetOptimizer.js.map