"use client"

import { taskRelease } from "@/components/label/api/task"
import { Task } from "@/components/label/api/task/typing"
import { usePermissionStore } from "@/components/label/store/auth"
import { Button, Group, Modal, Stack, Switch, Text } from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"

export default function ReleaseModal(props: {
  opened: boolean
  record: Task.DataProps | null
  onClose: (refresh?: boolean) => void
}) {
  const { opened, record, onClose } = props
  const operation_uid = usePermissionStore((s) => s.user_id)

  const form = useForm({
    initialValues: {
      reject: false,
    },
  })

  return (
    <Modal
      opened={opened}
      onClose={() => onClose()}
      title="释放任务"
      centered
      size={520}>
      <form
        onSubmit={form.onSubmit(async (values) => {
          const opUid = typeof operation_uid === "number" ? operation_uid : Number(operation_uid ?? 0)
          if (!record?.id || !opUid || !record.current_uid) {
            notifications.show({
              color: "red",
              title: "操作失败",
              message: "缺少必要参数",
            })
            return
          }
          try {
            await taskRelease({
              operation_uid: opUid,
              reject: values.reject,
              task_ids: [record.id],
              task_status: record.label_status,
              uid: record.current_uid,
            })
            notifications.show({
              color: "green",
              title: "操作成功",
              message: "已释放任务",
            })
            onClose(true)
          } catch (e) {
            notifications.show({
              color: "red",
              title: "操作失败",
              message: e instanceof Error ? e.message : "请求失败",
            })
          }
        })}>
        <Stack gap="sm">
          <Text size="sm" c="dimmed">
            当前任务：{record?.id ?? "-"}（状态：{record?.label_status ?? "-"}）
          </Text>
          <Switch
            label="是否返工"
            checked={form.values.reject}
            onChange={(e) => form.setFieldValue("reject", e.currentTarget.checked)}
          />
          <Group justify="flex-end" gap="sm">
            <Button variant="default" onClick={() => onClose()}>
              取消
            </Button>
            <Button type="submit" color="red">
              确定释放
            </Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}

