import type { ColumnDef } from "@tanstack/react-table"
import { SearchIcon } from "lucide-react"
import { useMemo, useState } from "react"
import DataTable from "@/components/data-table"
import Page from "@/components/page"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  cutAccount,
  DEFAULT_FILTERS,
  formatOrderType,
  type OrderFilters,
  type OrderItem,
  PACKAGE_OPTIONS,
  totalConnections,
} from "@/lib/models/order"
import { MOCK_ORDERS, MOCK_PRODUCTS } from "./mock"

function formatMoney(value: number): string {
  return value.toFixed(2)
}

function formatDate(value: string): string {
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  return `${year}.${month}.${day}`
}

function AccountCell({ accounts }: { accounts: string }) {
  const isCut = accounts.length > 15
  if (!isCut) return <span className="truncate">{accounts}</span>

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <span className="cursor-default truncate">{cutAccount(accounts)}</span>
      </TooltipTrigger>
      <TooltipContent className="max-w-80 break-all">{accounts}</TooltipContent>
    </Tooltip>
  )
}

const columns: ColumnDef<OrderItem>[] = [
  {
    accessorKey: "CreateTime",
    header: "日期",
    cell: ({ row }) => formatDate(row.original.CreateTime),
  },
  {
    accessorKey: "OrderNo",
    header: "订单编号",
  },
  {
    accessorKey: "OrderType",
    header: "类型",
    cell: ({ row }) => formatOrderType(row.original.OrderType),
  },
  {
    accessorKey: "ProductName",
    header: "产品",
  },
  {
    accessorKey: "PackageName",
    header: "套餐",
  },
  {
    accessorKey: "Accounts",
    header: "账号",
    cell: ({ row }) => <AccountCell accounts={row.original.Accounts} />,
  },
  {
    accessorKey: "ConnectCount",
    header: "连接数",
    cell: ({ row }) => totalConnections(row.original),
  },
  {
    accessorKey: "DayPrice",
    header: "退款时长",
    cell: ({ row }) => formatMoney(row.original.DayPrice),
  },
  {
    accessorKey: "DayPrice",
    header: "退款单价",
    cell: ({ row }) => formatMoney(row.original.DayPrice),
  },
  {
    accessorKey: "PaymentAmount",
    header: "实付金额",
    cell: ({ row }) => formatMoney(row.original.PaymentAmount),
  },
  {
    accessorKey: "CouponAmount",
    header: "退款金额",
    cell: ({ row }) => formatMoney(row.original.CouponAmount),
  },
]

function matchOrders(list: typeof MOCK_ORDERS, filters: OrderFilters) {
  const keyword = filters.keyword.trim()

  return list.filter(order => {
    if (
      filters.orderType !== "0" &&
      order.OrderType !== Number(filters.orderType)
    ) {
      return false
    }
    if (
      filters.productId !== "0" &&
      order.ProductId !== Number(filters.productId)
    ) {
      return false
    }
    if (
      filters.packageName !== "0" &&
      order.PackageName !== filters.packageName
    ) {
      return false
    }
    if (
      keyword &&
      !order.OrderNo.includes(keyword) &&
      !order.Accounts.includes(keyword)
    ) {
      return false
    }
    if (filters.bTime && order.CreateTime.slice(0, 10) < filters.bTime) {
      return false
    }
    if (filters.eTime && order.CreateTime.slice(0, 10) > filters.eTime) {
      return false
    }
    return true
  })
}

export default function RefundOrdersPage() {
  const [filters, setFilters] = useState<OrderFilters>(DEFAULT_FILTERS)
  const [appliedFilters, setAppliedFilters] =
    useState<OrderFilters>(DEFAULT_FILTERS)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  const filtered = useMemo(
    () => matchOrders(MOCK_ORDERS, appliedFilters),
    [appliedFilters],
  )

  const paged = useMemo(
    () => filtered.slice((page - 1) * pageSize, page * pageSize),
    [filtered, page, pageSize],
  )

  const patch = (partial: Partial<OrderFilters>) =>
    setFilters({ ...filters, ...partial })

  const handleSearch = () => {
    setAppliedFilters(filters)
    setPage(1)
  }

  return (
    <Page>
      <div className="bg-white rounded-lg p-4 flex flex-wrap items-end gap-x-4 gap-y-3">
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-500 whitespace-nowrap">
            日期筛选：
          </span>
          <Input
            type="date"
            value={filters.bTime}
            onChange={e => patch({ bTime: e.target.value })}
            className="w-36"
            aria-label="开始时间"
          />
          <span className="text-sm text-gray-400">至</span>
          <Input
            type="date"
            value={filters.eTime}
            onChange={e => patch({ eTime: e.target.value })}
            className="w-36"
            aria-label="结束时间"
          />
        </div>

        <Select
          value={filters.productId}
          onValueChange={value => patch({ productId: value })}
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="全部产品" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="0">全部产品</SelectItem>
            {MOCK_PRODUCTS.map(product => (
              <SelectItem key={product.id} value={String(product.id)}>
                {product.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select
          value={filters.packageName}
          onValueChange={value => patch({ packageName: value })}
        >
          <SelectTrigger className="w-32">
            <SelectValue placeholder="全部套餐" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="0">全部套餐</SelectItem>
            {PACKAGE_OPTIONS.map(pkg => (
              <SelectItem key={pkg} value={pkg}>
                {pkg}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <div className="flex items-center gap-2">
          <Input
            value={filters.keyword}
            onChange={e => patch({ keyword: e.target.value })}
            onKeyDown={e => {
              if (e.key === "Enter") handleSearch()
            }}
            placeholder="账号"
            className="w-40"
          />
          <Button onClick={handleSearch}>
            <SearchIcon data-icon="inline-start" />
            查询
          </Button>
        </div>
      </div>

      <div className="bg-white rounded-lg p-4 flex flex-col gap-4">
        <h3 className="font-semibold text-lg">订单管理</h3>
        <DataTable
          data={paged}
          status="done"
          columns={columns}
          pagination={{
            page: page - 1,
            size: pageSize,
            total: filtered.length,
            onPageChange: setPage,
            onSizeChange: size => {
              setPageSize(size)
              setPage(1)
            },
          }}
        />
      </div>
    </Page>
  )
}
