"use client"

import {
  deleteDailyWorkData,
  getSelfDailyWorkList,
} from "@/components/label/api/daily"
import { Daily } from "@/components/label/api/daily/typing"
import { getSelfProjectList } from "@/components/label/api/project"
import { useAllUserStore } from "@/components/label/store/auth"
import {
  SettingContentPanel,
  SettingDataTable,
  SettingFilterActions,
  SettingFilterPanel,
  SettingHeaderActions,
  SettingListHeader,
  SettingPage,
  SettingPanel,
} from "@/components/setting/PageSurface"
import {
  ActionIcon,
  Badge,
  Button,
  Collapse,
  Group,
  Modal,
  MultiSelect,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
} from "@mantine/core"
import { modals } from "@mantine/modals"
import { notifications } from "@mantine/notifications"
import {
  IconChevronDown,
  IconChevronUp,
  IconPencil,
  IconPlus,
  IconRefresh,
  IconSearch,
  IconTrash,
} from "@tabler/icons-react"

import dayjs from "dayjs"
import { DataTableColumn, DataTableSortStatus } from "mantine-datatable"
import { useCallback, useEffect, useMemo, useState } from "react"
import DailyReportModal from "./components/DailyReportModal"
import {
  accountTypeOpts,
  actualTypeOpts,
  objTypeOpts,
  objTypeTextMap,
  performanceOpts,
  performanceTextMap,
  setTypeOpts,
  workTypeOpts,
} from "./config"

type LeaderTreeNode = {
  title?: string
  value?: string | number
  children?: LeaderTreeNode[]
}

function flattenLeaderTree(
  nodes: LeaderTreeNode[],
  prefixTitle: string[] = []
): Array<{ label: string; value: string }> {
  const result: Array<{ label: string; value: string }> = []

  nodes.forEach((node) => {
    const title = node.title ?? ""
    const nextPrefix = title ? [...prefixTitle, title] : prefixTitle
    const children = node.children ?? []
    const hasChildren = children.length > 0
    const valueRaw = node.value

    if (hasChildren) {
      result.push(...flattenLeaderTree(children, nextPrefix))
      return
    }

    if (valueRaw === undefined || valueRaw === null) return
    if (typeof valueRaw === "string" && valueRaw.includes("-")) return

    result.push({
      label: nextPrefix.join(" / "),
      value: String(valueRaw),
    })
  })

  return result
}

function weekDayText(day: number) {
  const list = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
  return list[day] ?? "-"
}

function toBoolean(value?: string) {
  if (value === "true") return true
  if (value === "false") return false
  return undefined
}

function toNumber(value?: string) {
  if (!value) return undefined
  const n = Number(value)
  return Number.isFinite(n) ? n : undefined
}

const DEFAULT_RECORDS_PER_PAGE_OPTIONS = [10, 15, 20, 50]

export default function PersonReportPage() {
  const treeData = useAllUserStore((s) => s.treeData)

  const leaderOptions = useMemo(() => {
    return flattenLeaderTree(treeData ?? [])
  }, [treeData])

  const defaultFilters = useMemo(() => {
    return {
      date_start: dayjs().subtract(6, "day").format("YYYY-MM-DD"),
      date_end: dayjs().format("YYYY-MM-DD"),
      set_type: "",
      actual_type: "",
      leader_uid: [] as string[],
      work_type: "",
      accounting_type: "",
      project_id: [] as string[],
      performance_accounting: "",
      obj_type: "",
    }
  }, [])

  const [projectOptions, setProjectOptions] = useState<
    Array<{ label: string; value: string }>
  >([])

  const [filters, setFilters] = useState(defaultFilters)
  const [appliedFilters, setAppliedFilters] = useState(defaultFilters)
  const [queryTrigger, setQueryTrigger] = useState(0)

  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [recordsPerPageOptions, setRecordsPerPageOptions] = useState<number[]>(
    () => [...DEFAULT_RECORDS_PER_PAGE_OPTIONS]
  )
  const [customPageSizeInput, setCustomPageSizeInput] = useState("")
  const [customPageSizeModalOpened, setCustomPageSizeModalOpened] =
    useState(false)
  const [totalItems, setTotalItems] = useState(0)
  const [loading, setLoading] = useState(false)
  const [records, setRecords] = useState<Daily.DailyWorkList[]>([])
  const [summary, setSummary] = useState<Daily.Summary | null>(null)

  const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({
    columnAccessor: "id",
    direction: "desc",
  })

  const [modalOpened, setModalOpened] = useState(false)
  const [editingRecord, setEditingRecord] =
    useState<Daily.DailyWorkList | null>(null)

  const [searchExpanded, setSearchExpanded] = useState(false)

  const queryParams = useMemo(() => {
    const params: Daily.Request = {
      page_number: page,
      page_size: pageSize,
      flag: 0,
      date_start: appliedFilters.date_start || undefined,
      date_end: appliedFilters.date_end || undefined,
      set_type: appliedFilters.set_type || undefined,
      actual_type: appliedFilters.actual_type || undefined,
      leader_uid: appliedFilters.leader_uid.length
        ? appliedFilters.leader_uid
            .map((v) => Number(v))
            .filter((v) => Number.isFinite(v))
        : undefined,
      work_type: appliedFilters.work_type || undefined,
      accounting_type: appliedFilters.accounting_type || undefined,
      project_id: appliedFilters.project_id.length
        ? appliedFilters.project_id
            .map((v) => Number(v))
            .filter((v) => Number.isFinite(v))
        : undefined,
      performance_accounting: toBoolean(appliedFilters.performance_accounting),
      obj_type: toNumber(appliedFilters.obj_type),
      order_by: `${sortStatus.columnAccessor} ${sortStatus.direction}`,
    }

    Object.keys(params).forEach((k) => {
      const key = k as keyof Daily.Request
      const value = params[key]
      if (value === "" || value === null) delete params[key]
      if (Array.isArray(value) && value.length === 0) delete params[key]
      if (value !== 0 && value !== false && value !== "" && !value)
        delete params[key]
    })

    return params
  }, [
    appliedFilters,
    page,
    pageSize,
    sortStatus.columnAccessor,
    sortStatus.direction,
  ])

  const load = useCallback(async () => {
    if (!queryTrigger) return
    setLoading(true)
    try {
      const res = await getSelfDailyWorkList(queryParams)
      setRecords(res?.daily_work_list ?? [])
      setTotalItems(res?.total_items ?? 0)
      setSummary(res?.total_summary ?? null)
    } catch (e) {
      setRecords([])
      setTotalItems(0)
      setSummary(null)
      notifications.show({
        color: "red",
        title: "加载失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    } finally {
      setLoading(false)
    }
  }, [queryParams, queryTrigger])

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

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

  const openCustomPageSizeModal = useCallback(() => {
    setCustomPageSizeModalOpened(true)
  }, [])

  const closeCustomPageSizeModal = useCallback(() => {
    setCustomPageSizeModalOpened(false)
    setCustomPageSizeInput("")
  }, [])

  const handleAddCustomPageSize = useCallback(() => {
    const rawValue = customPageSizeInput.trim()
    if (!rawValue) return
    const size = Number(rawValue)
    if (!Number.isInteger(size) || size <= 0) {
      notifications.show({
        color: "red",
        title: "输入无效",
        message: "请填写大于 0 的整数条数",
      })
      return
    }
    if (recordsPerPageOptions.includes(size)) {
      notifications.show({
        color: "blue",
        title: "已存在",
        message: `每页 ${size} 条已在可选项中`,
      })
      return
    }
    setRecordsPerPageOptions((prev) => [...prev, size].sort((a, b) => a - b))
    closeCustomPageSizeModal()
    notifications.show({
      color: "green",
      title: "添加成功",
      message: `已新增每页 ${size} 条`,
    })
  }, [closeCustomPageSizeModal, customPageSizeInput, recordsPerPageOptions])

  const handleCustomPageSizeEnter = useCallback(
    (event: React.KeyboardEvent<HTMLInputElement>) => {
      if (event.key !== "Enter") return
      event.preventDefault()
      handleAddCustomPageSize()
    },
    [handleAddCustomPageSize]
  )

  const columns = useMemo(() => {
    const cols: DataTableColumn<Daily.DailyWorkList>[] = [
      { accessor: "id", title: "ID", width: 80, sortable: true },
      {
        accessor: "date",
        title: "日期",
        width: 120,
        sortable: true,
        render: (record) => record.date ?? "-",
      },
      {
        accessor: "week",
        title: "星期",
        width: 90,
        render: (record) =>
          record.date ? weekDayText(dayjs(record.date).day()) : "-",
      },
      {
        accessor: "set_type",
        title: "规定类型",
        width: 120,
        render: (record) => record.set_type ?? "-",
      },
      {
        accessor: "actual_type",
        title: "实际类型",
        width: 120,
        render: (record) => record.actual_type ?? "-",
      },
      { accessor: "leader_name", title: "任务组长", width: 120 },
      { accessor: "work_type", title: "工作类别", width: 140 },
      { accessor: "accounting_type", title: "核算方式", width: 140 },
      {
        accessor: "project_name",
        title: "项目名称",
        width: 220,
        render: (record) => (
          <Text
            size="sm"
            style={{
              maxWidth: 220,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}>
            {record.project_name ?? "-"}
          </Text>
        ),
      },
      {
        accessor: "performance_accounting",
        title: "绩效核算",
        width: 110,
        render: (record) => {
          if (record.performance_accounting === true)
            return <Badge color="green">{performanceTextMap.get(true)}</Badge>
          if (record.performance_accounting === false)
            return <Badge color="gray">{performanceTextMap.get(false)}</Badge>
          return "-"
        },
      },
      {
        accessor: "obj_type",
        title: "对象类型",
        width: 100,
        render: (record) => {
          if (record.obj_type === 0 || record.obj_type === 1)
            return objTypeTextMap.get(record.obj_type) ?? "-"
          return "-"
        },
      },
      { accessor: "start_time", title: "开始时间", width: 120 },
      { accessor: "end_time", title: "结束时间", width: 120 },
      {
        accessor: "work_time",
        title: "工时",
        width: 90,
        sortable: true,
      },
      { accessor: "rate", title: "额定倍率", width: 90 },
      {
        accessor: "standard_size",
        title: "标准量",
        width: 90,
        sortable: true,
      },
      {
        accessor: "completed_size",
        title: "完成量",
        width: 90,
        sortable: true,
      },
      {
        accessor: "residual_size",
        title: "余量",
        width: 90,
        sortable: true,
      },
      {
        accessor: "residual_work_time",
        title: "余量工时",
        width: 110,
        sortable: true,
      },
      {
        accessor: "remarks",
        title: "备注",
        width: 200,
        render: (record) => (
          <Text
            size="sm"
            style={{
              maxWidth: 200,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}>
            {record.remarks ?? "-"}
          </Text>
        ),
      },
      {
        accessor: "operation",
        title: "操作",
        width: 90,
        textAlign: "center",
        render: (record) => {
          const disabled = !!record.lock_status
          return (
            <Group gap={6} justify="center" wrap="nowrap">
              <ActionIcon
                variant="subtle"
                color="blue"
                disabled={disabled}
                onClick={() => {
                  if (disabled) return
                  setEditingRecord(record)
                  setModalOpened(true)
                }}>
                <IconPencil size={16} />
              </ActionIcon>
              <ActionIcon
                variant="subtle"
                color="red"
                disabled={disabled}
                onClick={() => {
                  if (disabled || !record.id) return
                  modals.openConfirmModal({
                    title: "删除日报",
                    centered: true,
                    children: (
                      <Text size="sm">
                        删除后不可恢复，你确定删除该日报吗？
                      </Text>
                    ),
                    labels: { confirm: "删除", cancel: "取消" },
                    confirmProps: { color: "red" },
                    onConfirm: async () => {
                      await deleteDailyWorkData(record.id as number)
                      notifications.show({
                        color: "green",
                        title: "操作成功",
                        message: "已删除日报",
                      })
                      load()
                    },
                  })
                }}>
                <IconTrash size={16} />
              </ActionIcon>
            </Group>
          )
        },
      },
    ]
    return cols
  }, [load])

  const summaryText = useMemo(() => {
    return {
      total_work_time: summary?.total_work_time ?? 0,
      total_standard_size: summary?.total_standard_size ?? 0,
      total_completed_size: summary?.total_completed_size ?? 0,
      total_residual_size: summary?.total_residual_size ?? 0,
      total_residual_work_time: summary?.total_residual_work_time ?? 0,
    }
  }, [summary])

  const asyncGetSelfProjectList = useCallback(async () => {
    const res = await getSelfProjectList()
    setProjectOptions(
      (res ?? []).map((r) => ({ label: r.label, value: String(r.value) }))
    )
  }, [])

  useEffect(() => {
    queueMicrotask(() => asyncGetSelfProjectList())
  }, [asyncGetSelfProjectList])

  return (
    <SettingPage>
      <SettingFilterPanel>
        <Stack gap="sm">
          <Group justify="space-between" wrap="wrap" gap="sm">
            <Group gap="xs">
              <Text fw={700}>筛选条件</Text>
              <Button
                variant="transparent"
                rightSection={
                  searchExpanded ? (
                    <IconChevronUp size={16} />
                  ) : (
                    <IconChevronDown size={16} />
                  )
                }
                onClick={() => setSearchExpanded((v) => !v)}>
                {searchExpanded ? "收起" : "展开"}
              </Button>
            </Group>

            <SettingFilterActions mt={0}>
              <Button
                variant="default"
                leftSection={<IconRefresh size={16} />}
                onClick={() => {
                  setFilters(defaultFilters)
                  setAppliedFilters(defaultFilters)
                  setPage(1)
                  setQueryTrigger((v) => v + 1)
                }}>
                重置
              </Button>
              <Button
                leftSection={<IconSearch size={16} />}
                onClick={() => {
                  setAppliedFilters(filters)
                  setPage(1)
                  setQueryTrigger((v) => v + 1)
                }}>
                查询
              </Button>
            </SettingFilterActions>
          </Group>
          <Collapse in={searchExpanded} transitionDuration={150} animateOpacity>
            <SimpleGrid cols={{ base: 1, sm: 2, md: 3, lg: 4 }} spacing="sm">
              <TextInput
                label="开始日期"
                type="date"
                value={filters.date_start}
                onChange={(e) =>
                  setFilters((s) => ({
                    ...s,
                    date_start: e.target.value,
                  }))
                }
              />
              <TextInput
                label="结束日期"
                type="date"
                value={filters.date_end}
                onChange={(e) => {
                  setFilters((s) => ({ ...s, date_end: e.target.value }))
                }}
              />
              <MultiSelect
                label="项目名称"
                data={projectOptions}
                searchable
                clearable
                value={filters.project_id}
                onChange={(v) => setFilters((s) => ({ ...s, project_id: v }))}
              />
              <MultiSelect
                label="任务组长"
                data={leaderOptions}
                searchable
                clearable
                value={filters.leader_uid}
                onChange={(v) => setFilters((s) => ({ ...s, leader_uid: v }))}
              />
              <MultiSelect
                label="规定类型"
                data={setTypeOpts}
                searchable
                clearable
                value={filters.set_type ? [filters.set_type] : []}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, set_type: v[0] ?? "" }))
                }
              />
              <MultiSelect
                label="出勤类型"
                data={actualTypeOpts}
                searchable
                clearable
                value={filters.actual_type ? [filters.actual_type] : []}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, actual_type: v[0] ?? "" }))
                }
              />
              <MultiSelect
                label="工作类别"
                data={workTypeOpts}
                searchable
                clearable
                value={filters.work_type ? [filters.work_type] : []}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, work_type: v[0] ?? "" }))
                }
              />
              <MultiSelect
                label="核算方式"
                data={accountTypeOpts}
                searchable
                clearable
                value={filters.accounting_type ? [filters.accounting_type] : []}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, accounting_type: v[0] ?? "" }))
                }
              />
              <MultiSelect
                label="绩效核算"
                data={performanceOpts}
                searchable
                clearable
                value={
                  filters.performance_accounting
                    ? [filters.performance_accounting]
                    : []
                }
                onChange={(v) =>
                  setFilters((s) => ({
                    ...s,
                    performance_accounting: v[0] ?? "",
                  }))
                }
              />
              <MultiSelect
                label="对象类型"
                data={objTypeOpts}
                searchable
                clearable
                value={filters.obj_type ? [filters.obj_type] : []}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, obj_type: v[0] ?? "" }))
                }
              />
            </SimpleGrid>
          </Collapse>
        </Stack>
      </SettingFilterPanel>

      <SettingContentPanel
        style={{
          flex: 1,
          minHeight: 0,
          display: "flex",
          flexDirection: "column",
          gap: 12,
        }}>
        <SettingListHeader
          title="我的日报"
          count={`${totalItems} 条`}
          actions={
            <SettingHeaderActions>
              <Button
                leftSection={<IconPlus size={16} />}
                onClick={() => {
                  setEditingRecord(null)
                  setModalOpened(true)
                }}>
                填写日报
              </Button>
              <Button
                variant="default"
                leftSection={<IconRefresh size={16} />}
                onClick={load}
                loading={loading}>
                刷新
              </Button>
            </SettingHeaderActions>
          }
        />
        <Stack gap={12} align="stretch" style={{ flex: 1, minHeight: 0 }}>
          <SettingDataTable<Daily.DailyWorkList>
            width="100%"
            minHeight={0}
            style={{ width: "100%", flex: 1 }}
            pinFirstColumn
            pinLastColumn
            scrollAreaProps={{ type: "auto" }}
            fetching={loading}
            records={records}
            columns={columns}
            totalRecords={totalItems}
            recordsPerPage={pageSize}
            page={page}
            onPageChange={setPage}
            onRecordsPerPageChange={(v) => {
              setPageSize(v)
              setPage(1)
            }}
            recordsPerPageOptions={recordsPerPageOptions}
            sortStatus={sortStatus}
            onSortStatusChange={(s) => {
              setSortStatus(s)
              setPage(1)
            }}
            renderPagination={({ Controls }) => (
              <Group
                justify="space-between"
                align="center"
                w="100%"
                gap="sm"
                wrap="wrap">
                <Group gap="xs" align="center" wrap="wrap">
                  <Controls.Text />
                  <Controls.PageSizeSelector />
                  <Button
                    variant="light"
                    color="gray"
                    size="xs"
                    onClick={openCustomPageSizeModal}>
                    自定义每页条数
                  </Button>
                </Group>
                <Controls.Pagination />
              </Group>
            )}
          />
          <SettingPanel radius="md" p="sm">
            <Group justify="space-between" wrap="wrap">
              <Text size="sm" fw={700}>
                当前页总计
              </Text>
              <Group gap="md">
                <Text size="sm">工时：{summaryText.total_work_time}</Text>
                <Text size="sm">标准量：{summaryText.total_standard_size}</Text>
                <Text size="sm">
                  完成量：{summaryText.total_completed_size}
                </Text>
                <Text size="sm">余量：{summaryText.total_residual_size}</Text>
                <Text size="sm">
                  余量工时：{summaryText.total_residual_work_time}
                </Text>
              </Group>
            </Group>
          </SettingPanel>
        </Stack>
      </SettingContentPanel>

      <DailyReportModal
        opened={modalOpened}
        record={editingRecord}
        projectOptions={projectOptions}
        onCloseAction={(refresh) => {
          setModalOpened(false)
          setEditingRecord(null)
          if (refresh) load()
        }}
      />

      <Modal
        opened={customPageSizeModalOpened}
        onClose={closeCustomPageSizeModal}
        title="添加每页条数"
        centered>
        <Stack gap="sm">
          <TextInput
            data-autofocus
            label="每页条数"
            placeholder="请输入大于 0 的整数，例如 99"
            value={customPageSizeInput}
            onChange={(event) =>
              setCustomPageSizeInput(event.currentTarget.value)
            }
            onKeyDown={handleCustomPageSizeEnter}
          />
          <Group justify="flex-end">
            <Button variant="default" onClick={closeCustomPageSizeModal}>
              取消
            </Button>
            <Button onClick={handleAddCustomPageSize}>添加</Button>
          </Group>
        </Stack>
      </Modal>
    </SettingPage>
  )
}
