"use client"

import { getUserTaskList } from "@/components/label/api/task"
import { Task } from "@/components/label/api/task/typing"
import {
  useBackUrlStore,
  usePermissionStore,
} from "@/components/label/store/auth"
import { TaskStatusEnum } from "@/components/label/utils/constants"
import { Badge, Button, Group, Text, UnstyledButton } from "@mantine/core"
import { IconRefresh } from "@tabler/icons-react"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useCallback, useEffect, useMemo, useState } from "react"

function getStatusColor(status?: number | null) {
  switch (status) {
    case 2:
      return "blue"
    case 4:
      return "yellow"
    case 6:
      return "orange"
    case 7:
      return "green"
    case 8:
      return "red"
    default:
      return "gray"
  }
}

export default function PersonalTaskTable() {
  const user_name = usePermissionStore((s) => s.user_name)
  const setBackProps = useBackUrlStore((s) => s.setBackProps)

  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(50)
  const [totalItems, setTotalItems] = useState(0)
  const [records, setRecords] = useState<Task.SimpleTaskItem[]>([])
  const [loading, setLoading] = useState(false)

  const totalPages = useMemo(() => {
    return Math.max(1, Math.ceil(totalItems / pageSize))
  }, [pageSize, totalItems])

  const load = useCallback(async () => {
    if (!user_name) return
    setLoading(true)
    try {
      const res = await getUserTaskList({
        page_number: page,
        page_size: pageSize,
      })
      setRecords(res?.simple_task_list ?? [])
      setTotalItems(res?.total_items ?? 0)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, user_name])

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

  useEffect(() => {
    if (page > totalPages) setPage(totalPages)
  }, [page, totalPages])

  const resetData = () => {
    if (page === 1) load()
    else setPage(1)
  }

  const [currentRowId, setCurrentRowId] = useState<number>(0)

  const originColumn = useMemo(() => {
    let column: DataTableColumn<Task.SimpleTaskItem>[] = [
      {
        accessor: "project_name",
        title: "项目名称",
        width: 150,
        render: (record: Task.SimpleTaskItem) => {
          return <Text>{record.project_name}</Text>
        },
      },
      {
        accessor: "id",
        title: "任务ID",
        width: 150,
        render: (record: Task.SimpleTaskItem) => {
          return (
            <UnstyledButton
              px={6}
              variant="transparent"
              onClick={async () => {
                setCurrentRowId(record.id)
                if ([4, 5, 6, 7].includes(record.label_type)) {
                  setBackProps(`/person/dashboard`)
                  if ([4, 5, 6].includes(record.label_type)) {
                    // router.replace(
                    //   `/image/label?project_id=${record.project_id}&task_id=${record.id}`
                    // )
                    window.location.href = `/image/label?project_id=${record.project_id}&task_id=${record.id}`
                  } else if ([7].includes(record.label_type)) {
                    // router.replace(
                    //   `/video/label?project_id=${record.project_id}&task_id=${record.id}`
                    // )
                    window.location.href = `/video/label?project_id=${record.project_id}&task_id=${record.id}`
                  }
                } else {
                  //   await runCommand(
                  //     record.id.toString(),
                  //     user_name,
                  //     user_password
                  //   )
                }
              }}
              title={record.id.toString()}
              c={"brand"}
              style={{
                fontSize: "14px",
                maxWidth: "100%",
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
              }}>
              {record.id}
            </UnstyledButton>
          )
        },
      },
      {
        accessor: "label_status",
        title: "状态",
        width: 80,
        render: (record: Task.SimpleTaskItem) => {
          return (
            <Badge
              color={getStatusColor(record.label_status)}
              style={{
                fontSize: "12px",
                padding: "2px 6px",
              }}>
              {TaskStatusEnum.get(record.label_status)}
            </Badge>
          )
        },
      },
      {
        accessor: "label_username",
        title: "标注员",
        width: 80,
      },
      {
        accessor: "review1_username",
        title: "审核员",
        width: 80,
      },
      {
        accessor: "review2_username",
        title: "复审员",
        width: 80,
      },
    ]
    return column
  }, [setBackProps])

  return (
    <Group
      gap="sm"
      h="100%"
      align="stretch"
      style={{ flexDirection: "column" }}>
      <Group justify="space-between" align="center">
        <Text fw={700} fz="lg" style={{ marginBottom: 8 }}>
          我的任务
        </Text>
        <Button
          size={"xs"}
          fz={"sm"}
          fw={500}
          radius="sm"
          onClick={resetData}
          loading={loading}
          leftSection={<IconRefresh size={16} />}>
          更新
        </Button>
      </Group>
      <Group
        gap={0}
        align="stretch"
        style={{ flex: 1, minHeight: 0, width: "100%" }}>
        <DataTable<Task.SimpleTaskItem>
          width="100%"
          style={{ width: "100%" }}
          styles={{
            header: {
              color: "var(--mantine-color-grey-text)",
              backgroundColor: "var(--mantine-datatable-striped-color)",
            },
          }}
          withTableBorder
          withRowBorders
          pinFirstColumn
          pinLastColumn
          rowBackgroundColor={({ id }) => {
            if (id === currentRowId)
              return "var(--mantine-datatable-highlight-on-hover-color-light, var(--mantine-datatable-highlight-on-hover-color))"
          }}
          scrollAreaProps={{ type: "auto" }}
          records={records}
          onRecordsPerPageChange={setPageSize}
          recordsPerPageOptions={[10, 15, 20]}
          columns={originColumn}
          totalRecords={totalItems}
          recordsPerPage={pageSize}
          page={page}
          onPageChange={setPage}
          noRecordsText="暂无数据"
          recordsPerPageLabel="当前页数"
        />
      </Group>
    </Group>
  )
}
