"use client"

import { ProjectDetail } from "@/components/label/api/project/typing"
import { getTaskList, taskAcquire } from "@/components/label/api/task"
import { Task } from "@/components/label/api/task/typing"
import {
  useBackUrlStore,
  useOwnTaskStore,
  usePermissionStore,
} from "@/components/label/store/auth"
import { OwnTaskStatusOpts } from "@/components/label/utils/constants"
import { Button, Group, Paper, Select, Stack, TextInput } from "@mantine/core"
import { notifications } from "@mantine/notifications"
import { IconRefresh } from "@tabler/icons-react"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useRouter, useSearchParams } from "next/navigation"
import { JSX, useCallback, useEffect, useMemo, useState } from "react"
import TaskStatusTag from "./components/TaskStatusTag"
import { runCommand } from "./util"

export default function OwnTaskTableContainer(props: {
  info: ProjectDetail.DataProps | undefined
  menuAction?: () => JSX.Element
  userEnums: {
    allEnum: Map<any, any>
    labelEnum: Map<any, any>
    review1Enum: Map<any, any>
    review2Enum: Map<any, any>
  }
}) {
  const { info, menuAction, userEnums } = props
  const urlParams = useSearchParams()
  const id = urlParams.get("id")
  const type = urlParams.get("type")
  const projectId =
    typeof id === "string" && !isNaN(Number(id)) ? Number(id) : -1

  const router = useRouter()
  const { setBackProps } = useBackUrlStore()
  const user_id = usePermissionStore((s) => s.user_id)
  const user_name = usePermissionStore((s) => s.user_name)
  const user_password = usePermissionStore((s) => s.user_password)

  const { params, total, resetParams, setPagination, setTotal } =
    useOwnTaskStore()

  const [form, setForm] = useState<{
    search_id: string
    search_status: string
  }>({
    search_id: "",
    search_status: "0",
  })

  const [records, setRecords] = useState<Task.DataProps[]>([])
  const [loading, setLoading] = useState(false)
  const [queryTrigger, setQueryTrigger] = useState(0)

  const [isLabel, isReview1, isReview2] = useMemo(() => {
    const uid = typeof user_id === "number" ? user_id : Number(user_id ?? 0)
    return [
      userEnums.labelEnum?.has(uid),
      userEnums.review1Enum?.has(uid),
      userEnums.review2Enum?.has(uid),
    ]
  }, [userEnums, user_id])

  const appliedParams = useMemo(() => {
    const uid = typeof user_id === "number" ? user_id : Number(user_id ?? 0)
    const next: Task.ListRequest = {
      ...params,
      page_number: params.page_number ?? 1,
      page_size: params.page_size ?? 20,
      current_uid: uid ? [uid] : undefined,
      project_id: projectId !== -1 ? [projectId] : undefined,
      get_data: false,
    }

    if (form.search_id) {
      const idValue = Number(form.search_id)
      if (Number.isFinite(idValue)) next.id = [idValue]
    }
    if (form.search_status !== "0") {
      const statusValue = Number(form.search_status)
      if (Number.isFinite(statusValue)) next.label_status = [statusValue]
    } else {
      delete next.label_status
    }
    return next
  }, [form.search_id, form.search_status, params, projectId, user_id])

  const load = useCallback(async () => {
    if (!queryTrigger) return
    if (projectId === -1) return
    setLoading(true)
    try {
      const res = await getTaskList(appliedParams)
      setRecords(res?.task_list ?? [])
      setTotal(res?.total_items ?? 0)
    } catch (e) {
      setRecords([])
      setTotal(0)
      notifications.show({
        color: "red",
        title: "加载失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    } finally {
      setLoading(false)
    }
  }, [appliedParams, projectId, queryTrigger, setTotal])

  useEffect(() => {
    load()
  }, [load])

  const handleAcquireTask = async (label_action: 1 | 2 | 3) => {
    const uid = typeof user_id === "number" ? user_id : Number(user_id ?? 0)
    if (!uid || projectId === -1) return
    try {
      await taskAcquire({
        uid,
        project_id: projectId,
        label_action,
      })
      notifications.show({
        color: "green",
        title: "操作成功",
        message: "领取成功",
      })
      setQueryTrigger((v) => v + 1)
    } catch (e) {
      notifications.show({
        color: "red",
        title: "领取失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    }
  }

  const columns = useMemo(() => {
    const cols: DataTableColumn<Task.DataProps>[] = [
      {
        accessor: "id",
        title: "任务ID",
        width: 100,
        render: (record) => (
          <Button
            variant="subtle"
            size="xs"
            style={{ paddingLeft: 6, paddingRight: 6 }}
            onClick={async () => {
              const backUrl = type
                ? `/management/person/collection/detail?id=${projectId}&type=${type}`
                : `/management/person/collection/detail?id=${projectId}`
              setBackProps(backUrl, "own")

              if (info && [4, 5, 6].includes(info.label_type)) {
                router.push(
                  `/label?project_id=${projectId}&task_id=${record.id}`
                )
              } else {
                await runCommand(
                  String(record.id),
                  user_name ?? "",
                  user_password ?? ""
                )
              }
            }}>
            {record.id}
          </Button>
        ),
      },
      {
        accessor: "label_status",
        title: "状态",
        width: 120,
        render: (record) => (
          <TaskStatusTag
            status={record.label_status}
            rejected={record.rejected}
          />
        ),
      },
      {
        accessor: "label_object_size.object_size",
        title: "对象总数",
        width: 110,
        render: (record) => record.label_object_size?.object_size ?? "-",
      },
      {
        accessor: "label_object_size.valid_size",
        title: "有效数",
        width: 100,
        render: (record) => record.label_object_size?.valid_size ?? "-",
      },
      {
        accessor: "label_object_size.new_size",
        title: "新增数",
        width: 100,
        render: (record) => record.label_object_size?.new_size ?? "-",
      },
      {
        accessor: "label_object_size.prelabel_size",
        title: "预标注总数",
        width: 120,
        render: (record) => record.label_object_size?.prelabel_size ?? "-",
      },
      {
        accessor: "label_object_size.prelabel_modify_size",
        title: "预标注修改数",
        width: 130,
        render: (record) =>
          record.label_object_size?.prelabel_modify_size ?? "-",
      },
      {
        accessor: "label_object_size.first_comment_size",
        title: "批注一轮",
        width: 110,
        render: (record) => record.label_object_size?.first_comment_size ?? "-",
      },
      {
        accessor: "label_object_size.second_comment_size",
        title: "批注二轮",
        width: 110,
        render: (record) =>
          record.label_object_size?.second_comment_size ?? "-",
      },
    ]
    return cols
  }, [info, projectId, router, setBackProps, type, user_name, user_password])

  return (
    <Stack gap="sm" style={{ flex: 1, minHeight: 0 }}>
      <Paper
        withBorder
        p="sm"
        radius="md"
        style={{ borderColor: "rgba(0,0,0,0.06)" }}>
        <Stack gap="sm">
          {menuAction ? <div>{menuAction()}</div> : null}
          <Group justify="space-between" wrap="wrap" gap="sm">
            <Group gap="sm" wrap="wrap">
              <TextInput
                size="xs"
                label="任务ID"
                value={form.search_id}
                onChange={(e) =>
                  setForm((s) => ({ ...s, search_id: e.currentTarget.value }))
                }
                style={{ width: 160 }}
              />
              <Select
                size="xs"
                label="状态"
                data={Object.entries(OwnTaskStatusOpts).map(
                  ([value, label]) => ({
                    value,
                    label,
                  })
                )}
                value={form.search_status}
                onChange={(v) =>
                  setForm((s) => ({ ...s, search_status: v ?? "0" }))
                }
                allowDeselect={false}
                style={{ width: 160 }}
              />
              <Button
                size="xs"
                leftSection={<IconRefresh size={16} />}
                loading={loading}
                onClick={() => {
                  setPagination(1, params.page_size ?? 20)
                  setQueryTrigger((v) => v + 1)
                }}>
                刷新
              </Button>
            </Group>

            <Group gap="xs" wrap="wrap">
              <Button
                size="xs"
                variant="default"
                disabled={!isLabel}
                onClick={() => handleAcquireTask(1)}>
                领取标注
              </Button>
              <Button
                size="xs"
                variant="default"
                disabled={!isReview1}
                onClick={() => handleAcquireTask(2)}>
                领取审核
              </Button>
              <Button
                size="xs"
                variant="default"
                disabled={!isReview2}
                onClick={() => handleAcquireTask(3)}>
                领取复审
              </Button>
              <Button
                size="xs"
                variant="default"
                onClick={() => {
                  resetParams()
                  setForm({ search_id: "", search_status: "0" })
                  setQueryTrigger((v) => v + 1)
                }}>
                重置
              </Button>
              <Button
                size="xs"
                onClick={() => {
                  setPagination(1, params.page_size ?? 20)
                  setQueryTrigger((v) => v + 1)
                }}>
                查询
              </Button>
            </Group>
          </Group>
        </Stack>
      </Paper>

      <Group gap={0} align="stretch" style={{ flex: 1, minHeight: 0 }}>
        <DataTable<Task.DataProps>
          width="100%"
          style={{ width: "100%" }}
          withTableBorder
          withRowBorders
          pinFirstColumn
          pinLastColumn
          scrollAreaProps={{ type: "auto" }}
          fetching={loading}
          records={records}
          columns={columns}
          totalRecords={total}
          recordsPerPage={params.page_size ?? 20}
          page={params.page_number ?? 1}
          onPageChange={(p) => {
            setPagination(p, params.page_size ?? 20)
            setQueryTrigger((v) => v + 1)
          }}
          onRecordsPerPageChange={(s) => {
            setPagination(1, s)
            setQueryTrigger((v) => v + 1)
          }}
          recordsPerPageOptions={[10, 20, 50, 100]}
          noRecordsText="暂无数据"
        />
      </Group>
    </Stack>
  )
}
