"use client"

import { getUserTaskList } from "@/components/label/api/task"
import {
  useBackUrlStore,
  usePermissionStore,
} from "@/components/label/store/auth"
import { TaskStatusEnum } from "@/components/label/utils/constants"
import {
  Anchor,
  Badge,
  Button,
  Group,
  Pagination,
  ScrollArea,
  Select,
  Table,
  Text,
} from "@mantine/core"
import { IconRefresh } from "@tabler/icons-react"
import { useRouter } from "next/navigation"
import { useCallback, useEffect, useMemo, useState } from "react"

const pageSizeOptions = [50, 100, 200]

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 router = useRouter()
  const user_name = usePermissionStore((s) => s.user_name)
  const user_password = usePermissionStore((s) => s.user_password)
  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<any[]>([])
  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)
  }

  return (
    <Group
      gap="sm"
      h="100%"
      align="stretch"
      style={{ flexDirection: "column" }}>
      <Group justify="flex-end">
        <Button
          variant="filled"
          onClick={resetData}
          loading={loading}
          leftSection={<IconRefresh size={16} />}>
          更新
        </Button>
      </Group>
      <Group gap={0} align="stretch" style={{ flex: 1, minHeight: 0 }}>
        <ScrollArea style={{ flex: 1 }}>
          <Table withTableBorder withColumnBorders striped highlightOnHover>
            <Table.Thead>
              <Table.Tr>
                <Table.Th style={{ width: 260 }}>项目名称</Table.Th>
                <Table.Th style={{ width: 110 }}>任务ID</Table.Th>
                <Table.Th style={{ width: 160 }}>状态</Table.Th>
                <Table.Th style={{ width: 90 }}>标注员</Table.Th>
                <Table.Th style={{ width: 90 }}>审核员</Table.Th>
                <Table.Th style={{ width: 90 }}>复审员</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {records.map((record) => (
                <Table.Tr key={record.id}>
                  <Table.Td>
                    <Text lineClamp={1}>{record.project_name ?? "-"}</Text>
                  </Table.Td>
                  <Table.Td>
                    <Anchor
                      onClick={async (e) => {
                        e.preventDefault()
                        const labelType = record.label_type
                        if ([4, 5, 6].includes(labelType)) {
                          setBackProps("/management/person/dashboard")
                          router.push(
                            `/label?project_id=${record.project_id}&task_id=${record.id}`
                          )
                          return
                        }
                        if (user_name && user_password) {
                          setBackProps("/management/person/dashboard")
                          router.push(
                            `/label?project_id=${record.project_id}&task_id=${record.id}`
                          )
                        }
                      }}
                      style={{ cursor: "pointer" }}>
                      {record.id ?? "-"}
                    </Anchor>
                  </Table.Td>
                  <Table.Td>
                    <Badge
                      color={getStatusColor(record.label_status)}
                      variant="light">
                      {`${TaskStatusEnum.get(record.label_status) ?? "-"}${
                        record.rejected ? "返工" : ""
                      }`}
                    </Badge>
                  </Table.Td>
                  <Table.Td>{record.label_username ?? "-"}</Table.Td>
                  <Table.Td>{record.review1_username ?? "-"}</Table.Td>
                  <Table.Td>{record.review2_username ?? "-"}</Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        </ScrollArea>
      </Group>
      <Group justify="space-between">
        <Group gap="xs">
          <Select
            w={120}
            value={String(pageSize)}
            data={pageSizeOptions.map((v) => String(v))}
            allowDeselect={false}
            onChange={(value) => {
              const next = Number(value)
              if (!Number.isFinite(next)) return
              setPageSize(next)
              setPage(1)
            }}
          />
        </Group>
        <Pagination value={page} onChange={setPage} total={totalPages} />
      </Group>
    </Group>
  )
}
