"use client"

import {
  getProjectList,
  getProjectTypeList,
  projectCollect,
} from "@/components/label/api/project"
import { Project } from "@/components/label/api/project/typing"
import {
  initAllParams,
  initCollectParams,
  initDynamicParams,
  useAllUserStore,
  useProjectStore,
} from "@/components/label/store/auth"
import {
  projectLabelTypeOpts,
  projectStatusOpts,
  STATUS_CODE,
} from "@/components/label/utils/constants"
import {
  ActionIcon,
  Badge,
  Button,
  Collapse,
  Group,
  Paper,
  Select,
  SimpleGrid,
  Stack,
  Text,
  TextInput,
} from "@mantine/core"
import { notifications } from "@mantine/notifications"
import {
  IconChevronDown,
  IconChevronUp,
  IconRefresh,
  IconSearch,
  IconStar,
  IconStarFilled,
} from "@tabler/icons-react"
import dayjs from "dayjs"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useRouter, useSearchParams } from "next/navigation"
import { useCallback, useEffect, useMemo, useState } from "react"

type PageType = "all" | "collect" | "dynamic"

function statusBadgeColor(status?: number | null) {
  if (!status) return "gray"
  if ([191, 199, 700].includes(status)) return "red"
  if ([580].includes(status)) return "yellow"
  if ([600].includes(status)) return "green"
  if ([201, 202, 203].includes(status)) return "cyan"
  return "blue"
}

function parseStatusValue(value?: string) {
  if (!value) return undefined
  if (value.includes(",")) {
    return value
      .split(",")
      .map((v) => Number(v))
      .filter((n) => Number.isFinite(n))
  }
  const n = Number(value)
  return Number.isFinite(n) ? [n] : undefined
}

export default function CollectionPage() {
  const router = useRouter()
  const urlParams = useSearchParams()
  const type = (urlParams.get("type") as PageType | null) ?? "collect"

  const { userOpts } = useAllUserStore()
  const {
    allParams,
    allTotal,
    collectParams,
    collectTotal,
    dynamicParams,
    dynamicTotal,
    resetParams,
    setSearchParams,
    setTotal,
  }: any = useProjectStore()

  const storeParams = useMemo(() => {
    return type === "collect"
      ? collectParams
      : type === "dynamic"
        ? dynamicParams
        : allParams
  }, [allParams, collectParams, dynamicParams, type])

  const total = useMemo(() => {
    return type === "collect"
      ? collectTotal
      : type === "dynamic"
        ? dynamicTotal
        : allTotal
  }, [allTotal, collectTotal, dynamicTotal, type])

  const [typeOpts, setTypeOpts] = useState<
    Array<{ label: string; value: string }>
  >([])
  const [loading, setLoading] = useState(false)
  const [records, setRecords] = useState<Project.DataProps[]>([])

  const [searchExpanded, setSearchExpanded] = useState(false)
  const [filters, setFilters] = useState(() => {
    return {
      project_name: "",
      project_type: "",
      status: "",
      owner: "",
      label_type: "",
      admin_user: "",
      start_date: dayjs().subtract(6, "day").format("YYYY-MM-DD"),
      end_date: dayjs().format("YYYY-MM-DD"),
    }
  })

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

  useEffect(() => {
    const initFormOpts = async () => {
      const res = await getProjectTypeList()
      setTypeOpts((res ?? []).map((name) => ({ label: name, value: name })))
    }
    initFormOpts()
  }, [])

  const queryParams = useMemo(() => {
    const base =
      type === "collect"
        ? { ...initCollectParams }
        : type === "dynamic"
          ? { ...initDynamicParams }
          : { ...initAllParams }

    const params: Project.ListRequest & any = {
      ...base,
      ...storeParams,
      page_number: storeParams.page_number ?? 1,
      page_size: storeParams.page_size ?? 15,
      project_name: appliedFilters.project_name || undefined,
      project_type: appliedFilters.project_type || undefined,
      owner: appliedFilters.owner || undefined,
      admin_user: appliedFilters.admin_user || undefined,
      start_date: appliedFilters.start_date || undefined,
      end_date: appliedFilters.end_date || undefined,
      label_type: appliedFilters.label_type
        ? Number(appliedFilters.label_type)
        : undefined,
      status: parseStatusValue(appliedFilters.status),
    }

    return params
  }, [appliedFilters, storeParams, type])

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

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

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

  const columns = useMemo(() => {
    const cols: DataTableColumn<Project.DataProps>[] = [
      {
        accessor: "id",
        title: "项目ID",
        width: 90,
      },
      {
        accessor: "name",
        title: "项目名称",
        width: 220,
        render: (record) => (
          <Button
            variant="subtle"
            size="xs"
            style={{
              paddingLeft: 6,
              paddingRight: 6,
              maxWidth: 220,
            }}
            onClick={() => {
              const url = type
                ? `/management/person/collection/detail?id=${record.id}&type=${type}`
                : `/management/person/collection/detail?id=${record.id}`
              router.push(url)
            }}>
            <Text
              size="sm"
              style={{
                maxWidth: 200,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}>
              {record.name}
            </Text>
          </Button>
        ),
      },
      {
        accessor: "project_type",
        title: "所属业务",
        width: 140,
        render: (record) => record.project_type ?? "-",
      },
      {
        accessor: "status",
        title: "状态",
        width: 110,
        render: (record) => (
          <Badge color={statusBadgeColor(record.status)}>
            {STATUS_CODE.get(record.status) ?? record.status}
          </Badge>
        ),
      },
      {
        accessor: "owner",
        title: "负责人",
        width: 120,
        render: (record) => record.owner ?? "-",
      },
      {
        accessor: "label_schema_name",
        title: "标注方案",
        width: 160,
        render: (record) => record.label_schema_name ?? "-",
      },
      {
        accessor: "update_at",
        title: "更新时间",
        width: 160,
        render: (record) => record.update_at ?? record.create_at ?? "-",
      },
      {
        accessor: "operation",
        title: "操作",
        width: 80,
        textAlign: "center",
        render: (record) => (
          <ActionIcon
            variant="subtle"
            color={record.is_collect ? "yellow" : "gray"}
            onClick={async () => {
              try {
                await projectCollect({
                  project_id: record.id,
                  is_collect: !record.is_collect,
                })
                notifications.show({
                  color: "green",
                  title: "操作成功",
                  message: record.is_collect ? "已取消收藏" : "已收藏",
                })
                load()
              } catch (e) {
                notifications.show({
                  color: "red",
                  title: "操作失败",
                  message: e instanceof Error ? e.message : "请求失败",
                })
              }
            }}>
            {record.is_collect ? (
              <IconStarFilled size={16} />
            ) : (
              <IconStar size={16} />
            )}
          </ActionIcon>
        ),
      },
    ]
    return cols
  }, [load, router, type])

  return (
    <Stack w="100%" h="calc(100vh - 56px)" p="md" gap="md">
      <Paper
        withBorder
        p="md"
        radius="md"
        style={{ borderColor: "rgba(0,0,0,0.06)" }}>
        <Group justify="space-between" wrap="wrap" gap="sm">
          {/* <SegmentedControl
            value={type}
            data={[
              { label: "全部项目", value: "all" },
              { label: "我的收藏", value: "collect" },
              { label: "动态项目", value: "dynamic" },
            ]}
            onChange={(v) => {
              const next = v as PageType
              router.replace(`/management/person/collection?type=${next}`)
            }}
          /> */}
          <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={() => {
                resetParams(type)
                const next = {
                  project_name: "",
                  project_type: "",
                  status: "",
                  owner: "",
                  label_type: "",
                  admin_user: "",
                  start_date: dayjs().subtract(6, "day").format("YYYY-MM-DD"),
                  end_date: dayjs().format("YYYY-MM-DD"),
                }
                setFilters(next)
                setAppliedFilters(next)
                setQueryTrigger((v) => v + 1)
              }}>
              重置
            </Button>
            <Button
              size="xs"
              radius="xs"
              leftSection={<IconSearch size={16} />}
              onClick={() => {
                setSearchParams({ ...storeParams, page_number: 1 }, type)
                setAppliedFilters(filters)
                setQueryTrigger((v) => v + 1)
              }}>
              查询
            </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
                label="项目名称"
                size="xs"
                radius="xs"
                value={filters.project_name}
                onChange={(e) =>
                  setFilters((s) => ({
                    ...s,
                    project_name: e.currentTarget.value,
                  }))
                }
              />
              <Select
                label="所属业务"
                size="xs"
                radius="xs"
                searchable
                clearable
                data={typeOpts}
                value={filters.project_type || null}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, project_type: v ?? "" }))
                }
              />
              <Select
                label="状态"
                size="xs"
                radius="xs"
                searchable
                data={projectStatusOpts.map((o) => ({
                  label: o.label,
                  value: o.label,
                }))}
                value={filters.status}
                onChange={(v) => setFilters((s) => ({ ...s, status: v ?? "" }))}
              />
              <TextInput
                label="负责人"
                size="xs"
                radius="xs"
                value={filters.owner}
                onChange={(e) =>
                  setFilters((s) => ({ ...s, owner: e.currentTarget.value }))
                }
              />
              <Select
                label="标注类型"
                size="xs"
                radius="xs"
                searchable
                clearable
                data={projectLabelTypeOpts.map((o) => ({
                  label: o.label,
                  value: String(o.value),
                }))}
                value={filters.label_type || null}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, label_type: v ?? "" }))
                }
              />
              <Select
                label="标注管理员"
                size="xs"
                radius="xs"
                searchable
                clearable
                data={userOpts.map((o) => ({
                  label: o.label,
                  value: String(o.value),
                }))}
                value={filters.admin_user || null}
                onChange={(v) =>
                  setFilters((s) => ({ ...s, admin_user: v ?? "" }))
                }
              />
              <TextInput
                label="开始日期"
                size="xs"
                radius="xs"
                type="date"
                value={filters.start_date}
                onChange={(e) =>
                  setFilters((s) => ({
                    ...s,
                    start_date: e.currentTarget.value,
                  }))
                }
              />
              <TextInput
                label="结束日期"
                size="xs"
                radius="xs"
                type="date"
                value={filters.end_date}
                onChange={(e) =>
                  setFilters((s) => ({ ...s, end_date: e.currentTarget.value }))
                }
              />
            </SimpleGrid>
          </Stack>
        </Collapse>
      </Paper>

      <Paper
        withBorder
        p="md"
        radius="md"
        style={{
          borderColor: "rgba(0,0,0,0.06)",
          flex: 1,
          minHeight: 0,
          display: "flex",
          flexDirection: "column",
        }}>
        <Group gap={0} align="stretch" style={{ flex: 1, minHeight: 0 }}>
          <DataTable<Project.DataProps>
            width="100%"
            style={{ width: "100%" }}
            withTableBorder
            withRowBorders
            pinFirstColumn
            pinLastColumn
            scrollAreaProps={{ type: "auto" }}
            fetching={loading}
            records={records}
            columns={columns}
            totalRecords={total}
            recordsPerPage={storeParams.page_size ?? 15}
            page={storeParams.page_number ?? 1}
            onPageChange={(p) => {
              setSearchParams({ ...storeParams, page_number: p }, type)
              setQueryTrigger((v) => v + 1)
            }}
            onRecordsPerPageChange={(s) => {
              setSearchParams(
                { ...storeParams, page_number: 1, page_size: s },
                type
              )
              setQueryTrigger((v) => v + 1)
            }}
            recordsPerPageOptions={[10, 15, 20, 50]}
            noRecordsText="暂无数据"
          />
        </Group>
      </Paper>
    </Stack>
  )
}
