"use client"

import {
  downloadSettlementForm,
  exportSettlementForm,
  getDownloadLog,
} from "@/components/label/api/workload"
import useAuth from "@/components/label/hooks/useAuth"
import {
  ActionIcon,
  Button,
  Group,
  Paper,
  Stack,
  Text,
} from "@mantine/core"
import { notifications } from "@mantine/notifications"
import { IconDownload, IconFileExport, IconRefresh } from "@tabler/icons-react"
import dayjs from "dayjs"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useCallback, useEffect, useMemo, useState } from "react"

function triggerDownload(blob: Blob, fileName: string) {
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement("a")
  link.href = url
  link.download = fileName
  link.click()
  window.URL.revokeObjectURL(url)
}

type LogRecord = {
  id: number
  create_at: string
  file_name: string
  create_user: string
}

export default function TeamCostPage() {
  const { isShow } = useAuth()

  const [records, setRecords] = useState<LogRecord[]>([])
  const [loading, setLoading] = useState(false)
  const [exporting, setExporting] = useState(false)

  const load = useCallback(async () => {
    try {
      setLoading(true)
      const res = await getDownloadLog()
      const list = (res ?? []) as LogRecord[]
      setRecords(list.sort((a, b) => (b.id ?? 0) - (a.id ?? 0)))
    } catch (e) {
      setRecords([])
      notifications.show({
        color: "red",
        title: "加载失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    } finally {
      setLoading(false)
    }
  }, [])

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

  const handleExport = async () => {
    try {
      setExporting(true)
      const time = dayjs().subtract(1, "month")
      const year = time.year()
      const month = time.month() + 1
      const blob = await exportSettlementForm({ year, month })
      const fileName = `结算表格_${year}_${String(month).padStart(2, "0")}.zip`
      triggerDownload(blob, fileName)
      notifications.show({
        color: "green",
        title: "导出成功",
        message: "已开始下载结算表格",
      })
      load()
    } catch (e) {
      notifications.show({
        color: "red",
        title: "导出失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    } finally {
      setExporting(false)
    }
  }

  const columns = useMemo(() => {
    const cols: DataTableColumn<LogRecord>[] = [
      { accessor: "id", title: "序号", width: 80 },
      {
        accessor: "create_at",
        title: "导出时间",
        width: 200,
        render: (record) =>
          record.create_at ? dayjs(record.create_at).format("YYYY-MM-DD HH:mm:ss") : "-",
      },
      { accessor: "file_name", title: "导出文件名", width: 280 },
      { accessor: "create_user", title: "操作人", width: 160 },
      {
        accessor: "operation",
        title: "操作",
        width: 90,
        textAlign: "center",
        render: (record) => (
          <ActionIcon
            variant="subtle"
            color="blue"
            disabled={!isShow("download")}
            onClick={async () => {
              try {
                const blob = await downloadSettlementForm({ id: record.id })
                const fileName = record.file_name || `结算表格_${record.id}.zip`
                triggerDownload(blob, fileName)
                notifications.show({
                  color: "green",
                  title: "下载成功",
                  message: "已开始下载文件",
                })
              } catch (e) {
                notifications.show({
                  color: "red",
                  title: "下载失败",
                  message: e instanceof Error ? e.message : "请求失败",
                })
              }
            }}>
            <IconDownload size={16} />
          </ActionIcon>
        ),
      },
    ]
    return cols
  }, [isShow])

  return (
    <Stack w="100%" h="calc(100vh - 56px)" p="md" gap="md">
      <Paper
        withBorder
        p="md"
        radius="md"
        style={{
          borderColor:
            "light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
        }}>
        <Group justify="space-between" wrap="wrap">
          <Group>
            <Button
              size="xs"
              radius="xs"
              leftSection={<IconFileExport size={16} />}
              onClick={handleExport}
              loading={exporting}
              disabled={!isShow("export")}>
              结算表格导出
            </Button>
            <ActionIcon onClick={load} variant="default" loading={loading}>
              <IconRefresh size={16} />
            </ActionIcon>
          </Group>
          <Text size="sm" c="dimmed">
            导出记录
          </Text>
        </Group>
      </Paper>

      <Paper
        withBorder
        p="md"
        radius="md"
        style={{
          borderColor:
            "light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
          flex: 1,
          minHeight: 0,
          display: "flex",
        }}>
        <DataTable<LogRecord>
          withTableBorder
          withRowBorders
          fetching={loading}
          records={records}
          columns={columns}
          noRecordsText="暂无数据"
          scrollAreaProps={{ type: "auto" }}
          style={{ width: "100%" }}
        />
      </Paper>
    </Stack>
  )
}
