import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import useAsync from 'react-use/esm/useAsync';
import { Progress, ResponseErrorPanel, Page, Header, Content, TabbedLayout, InfoCard } from '@backstage/core-components';
import { useApi } from '@backstage/core-plugin-api';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import { CodeInfoCard } from '../CodeInfoCard/CodeInfoCard.esm.js';
import { optimizationsApiRef } from '../../apis.esm.js';
import { getTimeFromNow } from '../../utils/dates.esm.js';
import { isEmptyObject, getRecommendedValue } from '../../utils/utils.esm.js';
import { OptimizationsBreakdownChart } from '../OptimizationsBreakdownChart/components/OptimizationsBreakdownChart.esm.js';
import { createUsageDatum, createRecommendationDatum } from '../OptimizationsBreakdownChart/utils/chart-data-format.esm.js';
import { OptimizationType, RecommendationType, UsageType, ResourceType } from '../OptimizationsBreakdownChart/types/chart.esm.js';
import { IntlProvider } from 'react-intl';
import messagesData from '../../locales/data.json.esm.js';

const RosDetailComponent = () => {
  const [recommendationTerm, setRecommendationTerm] = useState("shortTerm");
  const { id } = useParams();
  const api = useApi(optimizationsApiRef);
  const { value, loading, error } = useAsync(async () => {
    const apiQuery = {
      path: {
        recommendationId: id
      },
      query: {}
    };
    const response = await api.getRecommendationById(apiQuery);
    const payload = await response.json();
    return payload;
  }, []);
  if (loading) {
    return /* @__PURE__ */ React.createElement(Progress, null);
  }
  if (error) {
    return /* @__PURE__ */ React.createElement(ResponseErrorPanel, { error });
  }
  const handleChange = (event) => {
    setRecommendationTerm(event.target.value);
  };
  const containerData = [
    {
      key: "Last reported:",
      value: getTimeFromNow(value?.lastReported?.toString())
    },
    { key: "Cluster name:", value: value?.clusterAlias },
    { key: "Project name:", value: value?.project },
    { key: "Workload type:", value: value?.workloadType },
    { key: "Workload name:", value: value?.workload }
  ];
  const getCurrentYAMLCodeData = () => {
    const cpuLimits = value?.recommendations?.current?.limits?.cpu;
    const memoryLimits = value?.recommendations?.current?.limits?.memory;
    const cpuRequests = value?.recommendations?.current?.requests?.cpu;
    const memoryRequests = value?.recommendations?.current?.requests?.memory;
    const cpuLimitsValue = isEmptyObject(cpuLimits) ? "-" : `${cpuLimits?.amount}${cpuLimits?.format}`;
    const memoryLimitsValue = isEmptyObject(memoryLimits) ? "-" : `${memoryLimits?.amount}${memoryLimits?.format}`;
    const cpuRequestsValue = isEmptyObject(cpuRequests) ? "-" : `${cpuRequests?.amount}${cpuRequests?.format}`;
    const memoryRequestsValue = isEmptyObject(memoryRequests) ? "-" : `${memoryRequests?.amount}${memoryRequests?.format}`;
    const currentYAMLCodeData = {
      limits: {
        cpu: cpuLimitsValue,
        memory: memoryLimitsValue
      },
      requests: {
        cpu: cpuRequestsValue,
        memory: memoryRequestsValue
      }
    };
    return currentYAMLCodeData;
  };
  const getRecommendedYAMLCodeData = (duration, type) => {
    const currentValues = value?.recommendations?.current;
    const recommendedValues = value?.recommendations?.recommendationTerms?.[duration]?.recommendationEngines?.[type]?.config;
    if (currentValues && recommendedValues) {
      const cpuLimitsValue = getRecommendedValue(
        currentValues,
        recommendedValues,
        "limits",
        "cpu"
      );
      const memoryLimitsValue = getRecommendedValue(
        currentValues,
        recommendedValues,
        "limits",
        "memory"
      );
      const cpuRequestsValue = getRecommendedValue(
        currentValues,
        recommendedValues,
        "requests",
        "cpu"
      );
      const memoryRequestsValue = getRecommendedValue(
        currentValues,
        recommendedValues,
        "requests",
        "memory"
      );
      const recommendedYAMLCodeData = {
        limits: {
          cpu: cpuLimitsValue,
          memory: memoryLimitsValue
        },
        requests: {
          cpu: cpuRequestsValue,
          memory: memoryRequestsValue
        }
      };
      return recommendedYAMLCodeData;
    }
    return {
      limits: {
        cpu: "",
        memory: ""
      },
      requests: {
        cpu: "",
        memory: ""
      }
    };
  };
  const getChart = (usageType, recommendationType, optimizationType) => {
    const usageDatum = createUsageDatum(
      usageType,
      recommendationTerm,
      value?.recommendations
    );
    const limitDatum = createRecommendationDatum(
      recommendationTerm,
      usageDatum,
      recommendationType,
      ResourceType.limits,
      optimizationType,
      value?.recommendations
    );
    const requestDatum = createRecommendationDatum(
      recommendationTerm,
      usageDatum,
      recommendationType,
      ResourceType.requests,
      optimizationType,
      value?.recommendations
    );
    return /* @__PURE__ */ React.createElement(
      OptimizationsBreakdownChart,
      {
        baseHeight: 350,
        limitData: limitDatum,
        name: `utilization-${usageType}`,
        requestData: requestDatum,
        usageData: usageDatum
      }
    );
  };
  return /* @__PURE__ */ React.createElement(IntlProvider, { locale: "en", messages: messagesData.en }, /* @__PURE__ */ React.createElement(Page, { themeId: "tool" }, /* @__PURE__ */ React.createElement(
    Header,
    {
      title: "Resource Optimization",
      type: "Optimizations",
      typeLink: "/redhat-resource-optimization"
    }
  ), /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(Typography, { variant: "h4", paragraph: true }, value?.container), /* @__PURE__ */ React.createElement(Grid, { container: true, item: true, spacing: 1, xs: 8 }, containerData.map((item, index) => /* @__PURE__ */ React.createElement(Grid, { container: true, item: true, xs: 9, spacing: 1, key: index }, /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 4 }, /* @__PURE__ */ React.createElement(Typography, { variant: "body1" }, /* @__PURE__ */ React.createElement("b", null, item.key))), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 5 }, /* @__PURE__ */ React.createElement(Typography, { variant: "body1" }, item.value)))), /* @__PURE__ */ React.createElement(Grid, { container: true, item: true, xs: 9, spacing: 1 }, /* @__PURE__ */ React.createElement(Grid, { container: true, item: true, xs: 6, alignContent: "center" }, /* @__PURE__ */ React.createElement(Typography, { variant: "body1" }, /* @__PURE__ */ React.createElement("b", null, "View optimizations based on"))), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 3 }, /* @__PURE__ */ React.createElement(FormControl, { fullWidth: true, variant: "outlined" }, /* @__PURE__ */ React.createElement(
    Select,
    {
      id: "dropdown",
      value: recommendationTerm,
      onChange: handleChange
    },
    /* @__PURE__ */ React.createElement(MenuItem, { value: "shortTerm" }, "Last 24 hrs"),
    /* @__PURE__ */ React.createElement(MenuItem, { value: "mediumTerm" }, "Last 7 days"),
    /* @__PURE__ */ React.createElement(MenuItem, { value: "longTerm" }, "Last 15 days")
  ))))), /* @__PURE__ */ React.createElement(Box, { sx: { marginTop: 16 } }, /* @__PURE__ */ React.createElement(TabbedLayout, null, /* @__PURE__ */ React.createElement(TabbedLayout.Route, { path: "/cost?", title: "Cost optimizations" }, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
    CodeInfoCard,
    {
      cardTitle: "Current configuration",
      showCopyCodeButton: false,
      yamlCodeData: getCurrentYAMLCodeData()
    }
  )), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
    CodeInfoCard,
    {
      cardTitle: "Recommended configuration",
      showCopyCodeButton: true,
      yamlCodeData: getRecommendedYAMLCodeData(
        recommendationTerm,
        OptimizationType.cost
      )
    }
  ))), /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
    InfoCard,
    {
      title: /* @__PURE__ */ React.createElement(
        Typography,
        {
          variant: "body1",
          style: { fontWeight: "bold" }
        },
        "CPU utilization"
      )
    },
    getChart(
      UsageType.cpuUsage,
      RecommendationType.cpu,
      OptimizationType.cost
    )
  )), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
    InfoCard,
    {
      title: /* @__PURE__ */ React.createElement(
        Typography,
        {
          variant: "body1",
          style: { fontWeight: "bold" }
        },
        "Memory utilization"
      )
    },
    getChart(
      UsageType.memoryUsage,
      RecommendationType.memory,
      OptimizationType.cost
    )
  ))))), /* @__PURE__ */ React.createElement(
    TabbedLayout.Route,
    {
      path: "/performance",
      title: "Performance optimizations"
    },
    /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
      CodeInfoCard,
      {
        cardTitle: "Current configuration",
        showCopyCodeButton: false,
        yamlCodeData: getCurrentYAMLCodeData()
      }
    )), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
      CodeInfoCard,
      {
        cardTitle: "Recommended configuration",
        showCopyCodeButton: true,
        yamlCodeData: getRecommendedYAMLCodeData(
          recommendationTerm,
          OptimizationType.performance
        )
      }
    ))), /* @__PURE__ */ React.createElement(Grid, { container: true }, /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
      InfoCard,
      {
        title: /* @__PURE__ */ React.createElement(
          Typography,
          {
            variant: "body1",
            style: { fontWeight: "bold" }
          },
          "CPU utilization"
        )
      },
      getChart(
        UsageType.cpuUsage,
        RecommendationType.cpu,
        OptimizationType.performance
      )
    )), /* @__PURE__ */ React.createElement(Grid, { item: true, xs: 6 }, /* @__PURE__ */ React.createElement(
      InfoCard,
      {
        title: /* @__PURE__ */ React.createElement(
          Typography,
          {
            variant: "body1",
            style: { fontWeight: "bold" }
          },
          "Memory utilization"
        )
      },
      getChart(
        UsageType.memoryUsage,
        RecommendationType.memory,
        OptimizationType.performance
      )
    ))))
  ))))));
};

export { RosDetailComponent };
//# sourceMappingURL=RosDetailComponent.esm.js.map
