"use client"

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

export default function DispatchModal(props: {
  opened: boolean
  record: Task.DataProps | null
  userOptions: Array<{ label: string; value: string }>
  onCloseAction: (refresh?: boolean) => void
}) {
  const { opened, record, userOptions, onCloseAction } = props
  const operation_uid = usePermissionStore((s) => s.user_id)

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

  const taskStatusSrc = record?.label_status ?? 0
  const dstOptions =
    dispatchOpts[taskStatusSrc]?.opts?.map((o) => ({
      label: o.label,
      value: String(o.value),
    })) ?? []

  return (
    <Modal
      opened={opened}
      onClose={() => onCloseAction()}
      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) {
            notifications.show({
              color: "red",
              title: "操作失败",
              message: "缺少必要参数",
            })
            return
          }
          const taskStatusDst = Number(values.task_status_dst)
          if (!Number.isFinite(taskStatusDst)) {
            notifications.show({
              color: "red",
              title: "校验失败",
              message: "请选择目标状态",
            })
            return
          }

          const uidDst = values.uid_dst ? Number(values.uid_dst) : null
          if (values.uid_dst && !Number.isFinite(uidDst)) {
            notifications.show({
              color: "red",
              title: "校验失败",
              message: "请选择目标人员",
            })
            return
          }

          try {
            await taskDispatch({
              operation_uid: opUid,
              reject: values.reject,
              task_ids: [record.id],
              task_status_src: taskStatusSrc,
              task_status_dst: taskStatusDst,
              uid_src: record.current_uid ?? null,
              uid_dst: uidDst,
            })
            notifications.show({
              color: "green",
              title: "操作成功",
              message: "已调度任务",
            })
            onCloseAction(true)
          } catch (e) {
            notifications.show({
              color: "red",
              title: "操作失败",
              message: e instanceof Error ? e.message : "请求失败",
            })
          }
        })}>
        <Stack gap="sm">
          <Text size="sm" c="dimmed">
            当前任务：{record?.id ?? "-"}（源状态：{taskStatusSrc}）
          </Text>

          <Select
            label="目标状态"
            data={dstOptions}
            searchable
            clearable
            value={form.values.task_status_dst}
            onChange={(v) => form.setFieldValue("task_status_dst", v ?? "")}
          />

          <Select
            label="目标人员"
            data={userOptions}
            searchable
            clearable
            value={form.values.uid_dst}
            onChange={(v) => form.setFieldValue("uid_dst", v ?? "")}
          />

          <Switch
            label="是否返工"
            checked={form.values.reject}
            onChange={(e) =>
              form.setFieldValue("reject", e.currentTarget.checked)
            }
          />

          <Group justify="flex-end" gap="sm">
            <Button variant="default" onClick={() => onCloseAction()}>
              取消
            </Button>
            <Button type="submit">确定</Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}
