"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format, isBefore, isSameDay } from "date-fns"
import { Box, Loader2, Timer } from "lucide-react"
import { useSearchParams } from "next/navigation"
import { Suspense, useCallback, useMemo, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import {
  ResourceLong,
  ResourceShort,
  updateResource,
} from "@/actions/resources"
import { DataTable, useDataTable } from "@/components/data-table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import type { Resources } from "@/models/resources"

const filterSchema = z
  .object({
    user_phone: z.string().optional(),
    resource_no: z.string().optional(),
    status: z.string().optional(),
    type: z.string().optional(),
    created_at_start: z.string().optional(),
    created_at_end: z.string().optional(),
    expired: z.string().optional(),
  })
  .superRefine((data, ctx) => {
    if (data.created_at_start && data.created_at_end) {
      const start = new Date(data.created_at_start)
      const end = new Date(data.created_at_end)

      if (end < start) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: "结束时间不能早于开始时间",
          path: ["created_at_end"],
        })
      }
    }
  })

type FormValues = z.infer<typeof filterSchema>

interface FilterParams {
  user_phone?: string
  resource_no?: string
  active?: boolean
  mode?: number
  created_at_start?: Date
  created_at_end?: Date
  expired?: boolean
}

// 获取资源类型
function getResourceType(resource: Resources): number {
  if ("short" in resource && resource.short) {
    return resource.short.type
  }
  if ("long" in resource && resource.long) {
    return resource.long.type
  }
  return resource.type
}

// 获取资源详情对象
function getResourceDetail(resource: Resources) {
  if ("short" in resource && resource.short) {
    return resource.short
  }
  if ("long" in resource && resource.long) {
    return resource.long
  }
  return null
}

// 获取过期时间
function getExpireAt(resource: Resources): Date | null | undefined {
  if ("short" in resource && resource.short) {
    return resource.short.expire_at
  }
  if ("long" in resource && resource.long) {
    return resource.long.expire_at
  }
  return undefined
}

function getName(resource: Resources): string | null | undefined {
  if ("short" in resource && resource.short) {
    return resource.short.sku?.name
  }
  if ("long" in resource && resource.long) {
    return resource.long.sku?.name
  }
  return undefined
}

// 获取最近使用时间
function getLastAt(resource: Resources): Date | null | undefined {
  if ("short" in resource && resource.short) {
    return resource.short.last_at
  }
  if ("long" in resource && resource.long) {
    return resource.long.last_at
  }
  return undefined
}

// 资源类型徽章
function ResourceTypeBadge({ resource }: { resource: Resources }) {
  const type = getResourceType(resource)
  if (type === 1) {
    return (
      <div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
        <Timer size={20} />
        <span>包时</span>
      </div>
    )
  }
  if (type === 2) {
    return (
      <div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
        <Box size={20} />
        <span>包量</span>
      </div>
    )
  }
  return null
}

// 过期徽章
function ExpireBadge({ expireAt }: { expireAt: Date | null | undefined }) {
  if (!expireAt) return null
  if (isBefore(expireAt, new Date())) {
    return <Badge variant="destructive">过期</Badge>
  }
  return null
}

// 格式化日期
function formatDateTime(date: Date | null | undefined) {
  if (!date) return "-"
  return format(date, "yyyy-MM-dd HH:mm")
}

// 计算今日使用量
function getTodayUsage(lastAt: Date | null | undefined, daily: number) {
  if (lastAt && isSameDay(lastAt, new Date())) {
    return daily
  }
  return 0
}

export default function ResourcesPage() {
  return (
    <div>
      <Tabs defaultValue="short">
        <TabsList className="bg-card p-1.5 rounded-lg">
          <TabsTrigger
            value="short"
            className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
          >
            短效套餐
          </TabsTrigger>
          <TabsTrigger
            value="long"
            className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
          >
            长效套餐
          </TabsTrigger>
        </TabsList>
        <TabsContent value="short" className="flex flex-col gap-4">
          <ResourceList resourceType="short" />
        </TabsContent>
        <TabsContent value="long" className="flex flex-col gap-4">
          <ResourceList resourceType="long" />
        </TabsContent>
      </Tabs>
    </div>
  )
}

interface ResourceListProps {
  resourceType: "long" | "short"
}

function ResourceList({ resourceType }: ResourceListProps) {
  const searchParams = useSearchParams()
  const userId = searchParams.get("userId")
  const [filters, setFilters] = useState<FilterParams>({})
  const isLong = resourceType === "long"
  const listFn = isLong ? ResourceLong : ResourceShort
  const [updatingId, setUpdatingId] = useState<number | null>(null)
  const { control, handleSubmit, reset } = useForm<FormValues>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      user_phone: "",
      resource_no: "",
      status: "all",
      type: "all",
      created_at_start: "",
      created_at_end: "",
      expired: "all",
    },
  })

  const fetchResources = useCallback(
    (page: number, size: number) => {
      return listFn({ page, size, user_id: Number(userId), ...filters })
    },
    [listFn, filters, userId],
  )

  const table = useDataTable<Resources>(fetchResources)
  const refreshTable = useCallback(() => {
    setFilters(prev => ({ ...prev }))
  }, [])

  const handleStatusChange = useCallback(
    async (resource: Resources, newStatusValue: string) => {
      const newActive = newStatusValue === "0"
      if (newActive === resource.active) return
      setUpdatingId(resource.id)
      try {
        await updateResource({
          id: resource.id,
          active: newActive,
        })
        toast.success("更新成功", {
          description: `资源状态已更新为${newActive ? "启用" : "禁用"}`,
        })
        refreshTable()
      } catch (error) {
        console.error("更新状态失败:", error)
        toast.error("更新失败", {
          description: error instanceof Error ? error.message : "请稍后重试",
        })
      } finally {
        setUpdatingId(null)
      }
    },
    [refreshTable],
  )

  const onFilter = handleSubmit(data => {
    const result: FilterParams = {}
    if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
    if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
    if (data.status && data.status !== "all") {
      result.active = data.status === "0"
    }
    if (data.type && data.type !== "all") {
      result.mode = Number(data.type)
    }
    if (data.expired && data.expired !== "all") {
      result.expired = data.expired === "1"
    }
    if (data.created_at_start)
      result.created_at_start = new Date(data.created_at_start)
    if (data.created_at_end)
      result.created_at_end = new Date(data.created_at_end)

    setFilters(result)
    table.pagination.onPageChange(1)
  })

  const columns = useMemo(
    () => [
      {
        header: "会员号",
        accessorFn: (row: Resources) => row.user?.phone || "-",
      },
      {
        header: "套餐",
        cell: ({ row }: { row: { original: Resources } }) => {
          const resourceNo = row.original.resource_no
          const name = getName(row.original)
          const expireAt = getExpireAt(row.original)
          return (
            <div className="flex flex-col gap-1">
              <div>{name}</div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-500">{resourceNo}</span>
                <ExpireBadge expireAt={expireAt} />
              </div>
            </div>
          )
        },
      },
      {
        header: "类型",
        cell: ({ row }: { row: { original: Resources } }) => {
          return <ResourceTypeBadge resource={row.original} />
        },
      },
      {
        header: "IP时效",
        cell: ({ row }: { row: { original: Resources } }) => {
          const detail = getResourceDetail(row.original)
          const live = detail?.live
          if (live === undefined) return "-"
          return <span>{isLong ? `${live}小时` : `${live}分钟`}</span>
        },
      },
      {
        header: "使用情况",
        cell: ({ row }: { row: { original: Resources } }) => {
          const detail = getResourceDetail(row.original)
          const type = getResourceType(row.original)

          if (!detail) return <span>-</span>

          if (type === 1) {
            // 包时
            const todayUsage = getTodayUsage(detail.last_at, detail.daily || 0)
            return (
              <div className="flex gap-1">
                <span>
                  {todayUsage}/{detail.quota}
                </span>
              </div>
            )
          } else {
            // 包量
            if (isLong) {
              return (
                <div className="flex gap-1">
                  {detail.used < detail.quota ? (
                    <span className="text-green-500">正常</span>
                  ) : (
                    <span className="text-red-500">已用完</span>
                  )}
                  <span>|</span>
                  <span>
                    {detail.used}/{detail.quota}
                  </span>
                </div>
              )
            } else {
              return (
                <div className="flex gap-1">
                  <span>
                    {detail.used}/{detail.quota}
                  </span>
                </div>
              )
            }
          }
        },
      },
      {
        header: "最近使用时间",
        cell: ({ row }: { row: { original: Resources } }) => {
          const lastAt = getLastAt(row.original)
          return lastAt ? formatDateTime(lastAt) : "暂未使用"
        },
      },
      {
        header: "开通时间",
        cell: ({ row }: { row: { original: Resources } }) => {
          return formatDateTime(row.original.created_at)
        },
      },
      ...(!isLong
        ? [
            {
              header: "到期时间",
              cell: ({ row }: { row: { original: Resources } }) => {
                return formatDateTime(getExpireAt(row.original))
              },
            },
          ]
        : []),
      {
        id: "action",
        meta: { pin: "right" },
        header: "状态",
        cell: ({ row }: { row: { original: Resources } }) => {
          const resource = row.original
          const isLoading = updatingId === resource.id
          const currentActive = resource.active
          return (
            <div className="flex items-center gap-2">
              <Select
                value={currentActive ? "0" : "1"}
                onValueChange={val => handleStatusChange(resource, val)}
                disabled={isLoading}
              >
                <SelectTrigger className="min-w-20">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent className="min-w-(--radix-select-trigger-width)">
                  <SelectItem value="0">启用</SelectItem>
                  <SelectItem value="1">禁用</SelectItem>
                </SelectContent>
              </Select>
              {isLoading && (
                <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
              )}
            </div>
          )
        },
      },
    ],
    [isLong, updatingId, handleStatusChange],
  )

  return (
    <div className="space-y-3">
      <form onSubmit={onFilter} className="bg-white p-4 rounded-lg">
        <div className="flex flex-wrap items-end gap-4">
          <Controller
            name="user_phone"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-40 flex-none"
              >
                <FieldLabel>会员号</FieldLabel>
                <Input {...field} placeholder="请输入会员号" />
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="resource_no"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-40 flex-none"
              >
                <FieldLabel>套餐号</FieldLabel>
                <Input {...field} placeholder="请输入套餐号" />
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="status"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-32">
                <FieldLabel>状态</FieldLabel>
                <Select value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="全部" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="0">启用</SelectItem>
                    <SelectItem value="1">禁用</SelectItem>
                  </SelectContent>
                </Select>
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="type"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-32">
                <FieldLabel>类型</FieldLabel>
                <Select value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="全部" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="1">包时</SelectItem>
                    <SelectItem value="2">包量</SelectItem>
                  </SelectContent>
                </Select>
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="expired"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-32">
                <FieldLabel>是否过期</FieldLabel>
                <Select value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="全部" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="0">未过期</SelectItem>
                    <SelectItem value="1">已过期</SelectItem>
                  </SelectContent>
                </Select>
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="created_at_start"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-40 flex-none"
              >
                <FieldLabel>开始时间</FieldLabel>
                <Input type="date" {...field} />
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
          <Controller
            name="created_at_end"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-40 flex-none"
              >
                <FieldLabel>结束时间</FieldLabel>
                <Input type="date" {...field} />
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />
        </div>
        <FieldGroup className="flex-row justify-start mt-4 gap-2">
          <Button type="submit">筛选</Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => {
              reset()
              setFilters({})
              table.pagination.onPageChange(1)
            }}
          >
            重置
          </Button>
        </FieldGroup>
      </form>

      <Suspense fallback={<div className="text-center p-4">加载中...</div>}>
        <DataTable<Resources> {...table} columns={columns} />
      </Suspense>
    </div>
  )
}
