"use client"

import { getPersonProjectDashBoard } from "@/components/label/api/project"
import { Project } from "@/components/label/api/project/typing"
import { Button, Group, Text, UnstyledButton } from "@mantine/core"

import { IconRefresh } from "@tabler/icons-react"
import dayjs from "dayjs"
import duration from "dayjs/plugin/duration"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useRouter } from "next/navigation"
import { useCallback, useEffect, useMemo, useState } from "react"

dayjs.extend(duration)

function formatDurationSeconds(seconds?: number | null) {
  const value = seconds ?? 0
  if (!value) return "-"
  const durationObj = dayjs.duration(value, "seconds")
  const hours = durationObj.hours()
  const minutes = durationObj.minutes()
  if (hours) return `${hours}小时${minutes}分钟`
  if (minutes) return `${minutes}分钟`
  return "-"
}

export default function PersonalProjectTable() {
  const router = useRouter()
  const [records, setRecords] = useState<
    Project.PersonProjectDashboardResponseItem[]
  >([])
  const [loading, setLoading] = useState(false)

  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(50)
  const [totalItems, setTotalItems] = useState(0)

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

  const pageRecords = useMemo(() => {
    const start = (page - 1) * pageSize
    return records.slice(start, start + pageSize)
  }, [page, pageSize, records])

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getPersonProjectDashBoard()
      setRecords(res ?? [])
      setTotalItems(res?.length ?? 0)
      setPage(1)
    } finally {
      setLoading(false)
    }
  }, [])

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

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

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

  const originColumn = useMemo(() => {
    let column: DataTableColumn<Project.PersonProjectDashboardResponseItem>[] =
      [
        {
          accessor: "project_id",
          title: "项目ID",
          width: 150,
          render: (record: Project.PersonProjectDashboardResponseItem) => {
            return (
              <UnstyledButton
                px={6}
                variant="transparent"
                onClick={async () => {
                  setCurrentRowId(record.project_id)
                  router.push(`/project/info/detail?id=${record.project_id}`)
                }}
                title={record.project_id.toString()}
                c={"brand"}
                style={{
                  fontSize: "14px",
                  maxWidth: "100%",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}>
                {record.project_id}
              </UnstyledButton>
            )
          },
        },
        {
          accessor: "project_name",
          title: "项目名称",
          width: 160,
          render: (record: Project.PersonProjectDashboardResponseItem) => {
            return record.project_name ?? "-"
          },
        },
        {
          accessor: "project_type",
          title: "所属业务",
          width: 160,
          render: (record: Project.PersonProjectDashboardResponseItem) => {
            return (
              <Text
                title={record.project_id.toString()}
                style={{
                  fontSize: "14px",
                  maxWidth: "100%",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}>
                {record.project_type ?? "-"}
              </Text>
            )
          },
        },
        {
          accessor: "work_time",
          title: "任务耗时",
          width: 140,
          render: (record: Project.PersonProjectDashboardResponseItem) => {
            return formatDurationSeconds(record.work_time)
          },
        },
        {
          accessor: "project_label_type",
          title: "标注类别",
          width: 160,
          render: (record: Project.PersonProjectDashboardResponseItem) => {
            return record.project_label_type ?? "-"
          },
        },
      ]
    return column
  }, [router])

  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={load}
          loading={loading}
          leftSection={<IconRefresh size={16} />}>
          更新
        </Button>
      </Group>
      <Group
        gap={0}
        align="stretch"
        style={{ flex: 1, minHeight: 0, width: "100%" }}>
        <DataTable<Project.PersonProjectDashboardResponseItem>
          width="100%"
          style={{ width: "100%" }}
          styles={{
            header: {
              color: "var(--mantine-color-grey-text)",
              backgroundColor: "var(--mantine-datatable-striped-color)",
            },
          }}
          withTableBorder
          withRowBorders
          pinFirstColumn
          rowBackgroundColor={(record) => {
            if (record.project_id === currentRowId)
              return "var(--mantine-datatable-highlight-on-hover-color-light, var(--mantine-datatable-highlight-on-hover-color))"
          }}
          idAccessor="project_id"
          scrollAreaProps={{ type: "auto" }}
          records={pageRecords}
          onRecordsPerPageChange={setPageSize}
          recordsPerPageOptions={[10, 15, 20]}
          columns={originColumn}
          totalRecords={totalItems}
          recordsPerPage={pageSize}
          page={page}
          onPageChange={setPage}
          noRecordsText="暂无数据"
          recordsPerPageLabel="当前页数"
        />
      </Group>
    </Group>
  )
}
