"use client"

import { getTaskWorkFlow } from "@/components/label/api/task"
import { Button, Group, Modal, ScrollArea, Stack, Text } from "@mantine/core"
import { notifications } from "@mantine/notifications"
import { useEffect, useState } from "react"

export default function WorkflowModal(props: {
  opened: boolean
  taskId: number | null
  onClose: () => void
}) {
  const { opened, taskId, onClose } = props
  const [loading, setLoading] = useState(false)
  const [records, setRecords] = useState<any[]>([])

  useEffect(() => {
    if (!opened || !taskId) return
    const run = async () => {
      setLoading(true)
      try {
        const res = await getTaskWorkFlow(taskId)
        setRecords(res ?? [])
      } catch (e) {
        setRecords([])
        notifications.show({
          color: "red",
          title: "加载失败",
          message: e instanceof Error ? e.message : "请求失败",
        })
      } finally {
        setLoading(false)
      }
    }
    run()
  }, [opened, taskId])

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title="工作流"
      centered
      size={720}>
      <Stack gap="sm">
        <ScrollArea h={360} type="auto">
          <Stack gap="xs">
            {records.length ? (
              records.map((r, idx) => (
                <Text
                  key={idx}
                  size="sm"
                  style={{
                    fontFamily:
                      "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace",
                    whiteSpace: "pre-wrap",
                    wordBreak: "break-word",
                    background: "rgba(0,0,0,0.03)",
                    borderRadius: 6,
                    padding: 10,
                  }}>
                  {JSON.stringify(r, null, 2)}
                </Text>
              ))
            ) : (
              <Text size="sm" c="dimmed">
                {loading ? "加载中..." : "暂无数据"}
              </Text>
            )}
          </Stack>
        </ScrollArea>
        <Group justify="flex-end">
          <Button variant="default" onClick={onClose}>
            关闭
          </Button>
        </Group>
      </Stack>
    </Modal>
  )
}

