"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,
  usePermissionStore,
} from "@/components/label/store/auth"
import { OwnTaskStatusOpts } from "@/components/label/utils/constants"
import {
  ActionIcon,
  Button,
  Collapse,
  Flex,
  Group,
  Paper,
  Select,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
} from "@mantine/core"
import { notifications } from "@mantine/notifications"
import {
  IconChevronDown,
  IconChevronUp,
  IconRefresh,
  IconSearch,
} from "@tabler/icons-react"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useRouter, useSearchParams } from "next/navigation"
import { useCallback, useEffect, useMemo, useState } from "react"
import TaskStatusTag from "./components/TaskStatusTag"
import { runCommand } from "./util"

function createInitialFilters() {
  return {
    search_id: "",
    search_status: "0",
  }
}

export default function OwnTaskTableContainer(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

  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 [total, setTotal] = useState(0)

  const [pageNumber, setPageNumber] = useState(1)
  const [pageSize, setPageSize] = useState(15)

  const [searchExpanded, setSearchExpanded] = useState(false)

  const [filters, setFilters] = useState(() => createInitialFilters())
  const [form, setForm] = useState<{
    search_id: string
    search_status: string
  }>(createInitialFilters())

  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 = {
      page_number: pageNumber ?? 1,
      page_size: pageSize ?? 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,
    pageNumber,
    pageSize,
    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])

  useEffect(() => {
    queueMicrotask(() => {
      setQueryTrigger((v) => v + 1)
    })
  }, [])

  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="transparent"
            size="xs"
            style={{ paddingLeft: 6, paddingRight: 6 }}
            onClick={async () => {
              const backUrl = type
                ? `/management/project/detail?id=${projectId}&type=${type}`
                : `/management/project/detail?id=${projectId}`
              setBackProps(backUrl, "own")

              if (info && [4, 5, 6, 7].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="sm">
        <Group justify="space-between" wrap="wrap" gap="sm">
          <Group gap="xs">
            <Text fw={700}>我的任务</Text>
            <Button
              size="xs"
              variant="transparent"
              rightSection={
                searchExpanded ? (
                  <IconChevronUp size={16} />
                ) : (
                  <IconChevronDown size={16} />
                )
              }
              onClick={() => setSearchExpanded((v) => !v)}>
              {searchExpanded ? "收起筛选" : "展开筛选"}
            </Button>
          </Group>
          <Group gap="xs">
            <Button
              size="xs"
              radius={"xs"}
              variant="default"
              leftSection={<IconRefresh size={16} />}
              onClick={() => {
                const next = createInitialFilters()
                setFilters(next)
                setForm(next)
                setPageNumber(1)
              }}>
              重置
            </Button>
            <Button
              size="xs"
              radius={"xs"}
              leftSection={<IconSearch size={16} />}
              onClick={() => {
                setPageNumber(1)
                setForm({ ...filters })
              }}>
              查询
            </Button>
          </Group>
        </Group>
        <Collapse
          in={searchExpanded}
          transitionDuration={250}
          transitionTimingFunction="ease"
          animateOpacity>
          <Stack gap="sm" mt="sm">
            <SimpleGrid cols={{ base: 1, sm: 2, md: 3, lg: 4 }} spacing="sm">
              <TextInput
                size="xs"
                radius="xs"
                label="任务ID"
                value={filters.search_id}
                onChange={(e) =>
                  setFilters((s) => ({
                    ...s,
                    search_id: e.target.value,
                  }))
                }
                style={{ width: 160 }}
              />
              <Select
                size="xs"
                radius="xs"
                label="状态"
                data={Object.entries(OwnTaskStatusOpts).map(
                  ([value, label]) => ({
                    value,
                    label,
                  })
                )}
                value={filters.search_status}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, search_status: v ?? "0" }))
                }
                allowDeselect={false}
                style={{ width: 160 }}
              />
            </SimpleGrid>
          </Stack>
        </Collapse>
      </Paper>

      <Paper
        withBorder
        p="md"
        radius="sm"
        style={{
          flex: 1,
          minHeight: 0,
          display: "flex",
          flexDirection: "column",
        }}>
        <Stack gap={12} align="stretch" style={{ flex: 1, minHeight: 0 }}>
          <Flex justify={"space-between"} align="center" w="100%">
            <Flex gap={12}>
              <Button
                size="xs"
                radius="xs"
                variant="default"
                disabled={!isLabel}
                onClick={() => handleAcquireTask(1)}>
                领取标注
              </Button>
              <Button
                size="xs"
                radius="xs"
                variant="default"
                disabled={!isReview1}
                onClick={() => handleAcquireTask(2)}>
                领取审核
              </Button>
              <Button
                size="xs"
                radius="xs"
                variant="default"
                disabled={!isReview2}
                onClick={() => handleAcquireTask(3)}>
                领取复审
              </Button>
            </Flex>
            <ActionIcon onClick={load} variant="transparent">
              <IconRefresh size={16} />
            </ActionIcon>
          </Flex>
          <DataTable<Task.DataProps>
            width="100%"
            style={{ width: "100%" }}
            withTableBorder
            withRowBorders
            pinFirstColumn
            pinLastColumn
            scrollAreaProps={{ type: "auto" }}
            fetching={loading}
            records={records}
            columns={columns}
            totalRecords={total}
            recordsPerPage={pageSize}
            page={pageNumber}
            onPageChange={(p) => setPageNumber(p)}
            onRecordsPerPageChange={(s) => {
              setPageSize(s)
              setPageNumber(1)
            }}
            recordsPerPageOptions={[10, 15, 20]}
            noRecordsText="暂无数据"
            recordsPerPageLabel="当前页数"
          />
        </Stack>
      </Paper>
    </Stack>
  )
}
