"use client"

import { ProjectDetail } from "@/components/label/api/project/typing"
import { getTaskList } from "@/components/label/api/task"
import { Task } from "@/components/label/api/task/typing"
import {
  useAllTaskStore,
  usePermissionStore,
} from "@/components/label/store/auth"
import { TaskStatusOpts } from "@/components/label/utils/constants"
import {
  ActionIcon,
  Button,
  Group,
  Paper,
  Select,
  Stack,
  TextInput,
} from "@mantine/core"
import { notifications } from "@mantine/notifications"
import { IconArrowsShuffle, IconRoute, IconTrashX } from "@tabler/icons-react"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useSearchParams } from "next/navigation"
import { useCallback, useEffect, useMemo, useState } from "react"
import DispatchModal from "./components/DispatchModal"
import ReleaseModal from "./components/ReleaseModal"
import TaskStatusTag from "./components/TaskStatusTag"
import WorkflowModal from "./components/WorkflowModal"

export default function TaskTableContainer(props: {
  info: ProjectDetail.DataProps | undefined
  userEnums: {
    allEnum: Map<any, any>
    labelEnum: Map<any, any>
    review1Enum: Map<any, any>
    review2Enum: Map<any, any>
  }
}) {
  const { info, userEnums } = props
  false && console.log(info)

  const urlParams = useSearchParams()
  const id = urlParams.get("id")
  const projectId =
    typeof id === "string" && !isNaN(Number(id)) ? Number(id) : -1

  const currentUid = usePermissionStore((s) => s.user_id)
  false && console.log(currentUid)

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

  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 [workflowTaskId, setWorkflowTaskId] = useState<number | null>(null)
  const [dispatchRecord, setDispatchRecord] = useState<Task.DataProps | null>(
    null
  )
  const [releaseRecord, setReleaseRecord] = useState<Task.DataProps | null>(
    null
  )

  const userOptions = useMemo(() => {
    const arr: Array<{ label: string; value: string }> = []
    userEnums.allEnum?.forEach((label, value) => {
      arr.push({ label: String(label), value: String(value) })
    })
    return arr
  }, [userEnums.allEnum])

  const appliedParams = useMemo(() => {
    const obj: Task.ListRequest = {
      ...params,
      page_number: params.page_number ?? 1,
      page_size: params.page_size ?? 20,
      project_id: projectId !== -1 ? [projectId] : undefined,
      get_data: false,
    }
    if (form.search_id) {
      const idValue = Number(form.search_id)
      if (Number.isFinite(idValue)) obj.id = [idValue]
    }
    if (form.search_status !== "0") {
      const statusValue = Number(form.search_status)
      if (Number.isFinite(statusValue)) obj.label_status = [statusValue]
    } else {
      delete obj.label_status
    }
    return obj
  }, [form.search_id, form.search_status, params, projectId])

  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 columns = useMemo(() => {
    const cols: DataTableColumn<Task.DataProps>[] = [
      { accessor: "id", title: "任务ID", width: 90 },
      {
        accessor: "label_status",
        title: "状态",
        width: 130,
        render: (record) => (
          <TaskStatusTag
            status={record.label_status}
            rejected={record.rejected}
          />
        ),
      },
      {
        accessor: "current_username",
        title: "当前处理人",
        width: 120,
        render: (record) => record.current_username ?? "-",
      },
      {
        accessor: "label_username",
        title: "标注员",
        width: 120,
        render: (record) => record.label_username ?? "-",
      },
      {
        accessor: "review1_username",
        title: "审核员",
        width: 120,
        render: (record) => record.review1_username ?? "-",
      },
      {
        accessor: "review2_username",
        title: "复审员",
        width: 120,
        render: (record) => record.review2_username ?? "-",
      },
      {
        accessor: "label_object_size.object_size",
        title: "对象总数",
        width: 110,
        render: (record) => record.label_object_size?.object_size ?? "-",
      },
      {
        accessor: "operation",
        title: "操作",
        width: 140,
        textAlign: "center",
        render: (record) => (
          <Group gap={6} justify="center" wrap="nowrap">
            <ActionIcon
              variant="subtle"
              color="blue"
              onClick={() => setWorkflowTaskId(record.id)}
              title="工作流">
              <IconRoute size={16} />
            </ActionIcon>
            <ActionIcon
              variant="subtle"
              color="violet"
              onClick={() => setDispatchRecord(record)}
              title="调度">
              <IconArrowsShuffle size={16} />
            </ActionIcon>
            <ActionIcon
              variant="subtle"
              color="red"
              onClick={() => setReleaseRecord(record)}
              title="释放">
              <IconTrashX size={16} />
            </ActionIcon>
          </Group>
        ),
      },
    ]
    return cols
  }, [])

  return (
    <>
      <Stack gap="sm" style={{ flex: 1, minHeight: 0 }}>
        <Paper
          withBorder
          p="sm"
          radius="md"
          style={{
            borderColor:
              "light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
          }}>
          <Stack gap="sm">
            <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.target.value }))
                  }
                  style={{ width: 160 }}
                />
                <Select
                  size="xs"
                  label="状态"
                  data={Object.entries(TaskStatusOpts).map(
                    ([value, label]) => ({
                      value,
                      label,
                    })
                  )}
                  value={form.search_status}
                  onChange={(v) =>
                    setForm((s) => ({ ...s, search_status: v ?? "0" }))
                  }
                  allowDeselect={false}
                  style={{ width: 160 }}
                />
              </Group>

              <Group gap="xs" wrap="wrap">
                <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>

      <WorkflowModal
        opened={workflowTaskId !== null}
        taskId={workflowTaskId}
        onCloseAction={() => setWorkflowTaskId(null)}
      />
      <DispatchModal
        opened={dispatchRecord !== null}
        record={dispatchRecord}
        userOptions={userOptions}
        onCloseAction={(refresh) => {
          setDispatchRecord(null)
          if (refresh) setQueryTrigger((v) => v + 1)
        }}
      />
      <ReleaseModal
        opened={releaseRecord !== null}
        record={releaseRecord}
        onCloseAction={(refresh) => {
          setReleaseRecord(null)
          if (refresh) setQueryTrigger((v) => v + 1)
        }}
      />
    </>
  )
}
