/*!
 * 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, Flex, Button } from "@chakra-ui/react";
import { useState } from "react";
import { useTranslation } from "react-i18next";

import type { TaskInstanceResponse } from "openapi/requests/types.gen";
import { ClearTaskInstanceButton } from "src/components/Clear";
import { StateBadge } from "src/components/StateBadge";
import Time from "src/components/Time";
import { RouterLink } from "src/components/ui";
import { TaskLogContent } from "src/pages/TaskInstance/Logs/TaskLogContent";
import { useLogs } from "src/queries/useLogs";
import { getTaskInstanceLink } from "src/utils/links";

export const TaskLogPreview = ({
  taskInstance,
  wrap,
}: {
  readonly taskInstance: TaskInstanceResponse;
  readonly wrap: boolean;
}) => {
  const { t: translate } = useTranslation("dag");
  const [isExpanded, setIsExpanded] = useState(false);

  const {
    error,
    isLoading,
    parsedData: data,
  } = useLogs(
    {
      dagId: taskInstance.dag_id,
      limit: 100,
      logLevelFilters: ["error", "critical"],
      taskInstance,
      tryNumber: taskInstance.try_number,
    },
    {
      enabled: isExpanded,
      refetchInterval: false,
      retry: false,
    },
  );

  return (
    <Box borderRadius={4} borderStyle="solid" borderWidth={1} key={taskInstance.id} width="100%">
      <Flex alignItems="center" justifyContent="space-between" px={2} py={2}>
        <Box>
          <StateBadge mr={1} state={taskInstance.state} />
          {taskInstance.task_display_name}
          <Time datetime={taskInstance.run_after} ml={1} />
        </Box>
        <Flex gap={1}>
          <Button fontSize="sm" onClick={() => setIsExpanded(!isExpanded)} variant="ghost">
            {isExpanded
              ? translate("overview.failedLogs.hideLogs")
              : translate("overview.failedLogs.showLogs")}
          </Button>
          <ClearTaskInstanceButton taskInstance={taskInstance} />
          <RouterLink fontSize="sm" to={getTaskInstanceLink(taskInstance)}>
            {translate("overview.failedLogs.viewFullLogs")}
          </RouterLink>
        </Flex>
      </Flex>
      {isExpanded ? (
        <Box borderTopStyle="solid" borderTopWidth={1} maxHeight="200px" overflow="auto">
          <TaskLogContent
            error={error}
            expanded
            isLoading={isLoading}
            logError={error}
            parsedLogs={data.parsedLogs ?? []}
            wrap={wrap}
          />
        </Box>
      ) : undefined}
    </Box>
  );
};
