/*!
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import { Box, Separator, Heading, HStack, Stack } from "@chakra-ui/react";
import type { TaskInstanceState, TaskInstanceStateCount } from "openapi-gen/requests/types.gen";
import { useTranslation } from "react-i18next";
import { MdOutlineTask } from "react-icons/md";

import { MetricSection } from "./MetricSection";

type TaskInstanceMetricsProps = {
  readonly endDate?: string;
  readonly startDate: string;
  readonly stateCountLimit: number;
  readonly taskInstanceStates: TaskInstanceStateCount;
};

const TASK_STATES: Array<keyof TaskInstanceStateCount> = [
  "queued",
  "running",
  "success",
  "failed",
  "skipped",
  "removed",
  "scheduled",
  "restarting",
  "up_for_retry",
  "up_for_reschedule",
  "upstream_failed",
  "deferred",
  "awaiting_input",
  "no_status",
];

export const TaskInstanceMetrics = ({
  endDate,
  startDate,
  stateCountLimit,
  taskInstanceStates,
}: TaskInstanceMetricsProps) => {
  const { t: translate } = useTranslation();
  const total = Object.values(taskInstanceStates).reduce((sum, count) => sum + count, 0);
  // When any state hit the API's STATE_COUNT_CAP, the summed total is only a
  // lower bound, so per-state percentages computed from it are wrong (#67336).
  // Suppress percentages for the whole group in that case.
  const isTotalTruncated = Object.values(taskInstanceStates).some((count) => count >= stateCountLimit);

  return (
    <Box borderRadius={5} borderWidth={1} mt={2} p={4}>
      <HStack>
        <MdOutlineTask />
        <Heading size="md">{translate("taskInstance", { count: 2 })}</Heading>
      </HStack>
      <Separator my={3} />
      <Stack gap={4}>
        {TASK_STATES.sort((stateA, stateB) =>
          taskInstanceStates[stateA] > taskInstanceStates[stateB] ? -1 : 1,
        ).map((state) =>
          taskInstanceStates[state] > 0 ? (
            <MetricSection
              capped={taskInstanceStates[state] >= stateCountLimit}
              endDate={endDate}
              isTotalTruncated={isTotalTruncated}
              key={state}
              kind="task_instances"
              runs={taskInstanceStates[state]}
              startDate={startDate}
              state={state as TaskInstanceState}
              total={total}
            />
          ) : undefined,
        )}
      </Stack>
    </Box>
  );
};
