"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CheckCircle, Clock, XCircle } from "lucide-react"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getPageTrade } from "@/actions/trade"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
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 type { Trade } from "@/models/trade"

type FilterValues = {
  user_phone?: string
  inner_no?: string
  method?: number
  platform?: number
  status?: number
  created_at_start?: Date
  created_at_end?: Date
}
const filterSchema = z
  .object({
    user_phone: z
      .string()
      .optional()
      .transform(val => val?.trim()),
    inner_no: z
      .string()
      .optional()
      .transform(val => val?.trim()),
    method: z.string().optional(),
    platform: z.string().optional(),
    status: z.string().optional(),
    created_at_start: z.string().optional(),
    created_at_end: 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 FilterSchema = z.infer<typeof filterSchema>

export default function TradePage() {
  const [filters, setFilters] = useState<FilterValues>({})

  const { control, handleSubmit, reset } = useForm<FilterSchema>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      user_phone: "",
      inner_no: "",
      method: "all",
      platform: "all",
      status: "all",
      created_at_start: "",
      created_at_end: "",
    },
  })

  const fetchTrades = useCallback(
    (page: number, size: number) => {
      return getPageTrade({ page, size, ...filters })
    },
    [filters],
  )

  const table = useDataTable<Trade>(fetchTrades)
  const onFilter = handleSubmit(data => {
    const result: FilterValues = {}

    if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
    if (data.inner_no?.trim()) result.inner_no = data.inner_no.trim()
    if (data.method && data.method !== "all")
      result.method = Number(data.method)
    if (data.platform && data.platform !== "all")
      result.platform = Number(data.platform)
    if (data.status && data.status !== "all")
      result.status = Number(data.status)
    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)
  })

  return (
    <Page>
      {/* 筛选表单 */}
      <form onSubmit={onFilter} className="bg-card 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="inner_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="method"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-24">
                <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>
                    <SelectItem value="3">商福通</SelectItem>
                    <SelectItem value="4">商福通渠道支付宝</SelectItem>
                    <SelectItem value="5">商福通渠道微信</SelectItem>
                  </SelectContent>
                </Select>
                <FieldError>{fieldState.error?.message}</FieldError>
              </Field>
            )}
          />

          <Controller
            name="platform"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-24">
                <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="status"
            control={control}
            render={({ field, fieldState }) => (
              <Field data-invalid={fieldState.invalid} className="w-24">
                <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>
                    <SelectItem value="2">取消支付</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>
        <DataTable<Trade>
          {...table}
          columns={[
            {
              header: "创建时间",
              accessorKey: "created_at",
              cell: ({ row }) =>
                format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
            },
            { header: "会员号", accessorFn: row => row.user?.phone || "" },
            { header: "订单号", accessorKey: "inner_no" },
            { header: "购买套餐", accessorKey: "subject" },
            {
              header: "支付金额",
              accessorKey: "payment",
              cell: ({ row }) => {
                const payment =
                  typeof row.original.payment === "string"
                    ? parseFloat(row.original.payment)
                    : row.original.payment || 0
                return (
                  <div className="flex gap-1">
                    <span
                      className={
                        payment > 0 ? "text-green-500" : "text-orange-500"
                      }
                    >
                      ￥{payment.toFixed(2)}
                    </span>
                  </div>
                )
              },
            },
            {
              header: "支付状态",
              accessorKey: "status",
              cell: ({ row }) => {
                const status = row.original.status

                switch (status) {
                  case 0:
                    return (
                      <div className="flex items-center gap-2 text-yellow-600">
                        <Clock className="h-4 w-4" />
                        <span>待支付</span>
                      </div>
                    )
                  case 1:
                    return (
                      <div className="flex items-center gap-2 text-green-600">
                        <CheckCircle className="h-4 w-4" />
                        <span>支付成功</span>
                      </div>
                    )
                  case 2:
                    return (
                      <div className="flex items-center gap-2 text-gray-500">
                        <XCircle className="h-4 w-4" />
                        <span>取消支付</span>
                      </div>
                    )
                  default:
                    return <span className="text-gray-400">-</span>
                }
              },
            },
            {
              header: "支付平台",
              accessorKey: "platform",
              cell: ({ row }) => {
                const platform = row.original.platform
                if (!platform) return <span>-</span>
                return (
                  <div className="flex items-center gap-2">
                    {platform === 1 ? (
                      <span>电脑网站</span>
                    ) : platform === 2 ? (
                      <span>手机网站</span>
                    ) : (
                      <span>-</span>
                    )}
                  </div>
                )
              },
            },
            {
              header: "支付渠道",
              accessorKey: "method",
              cell: ({ row }) => {
                const methodMap: Record<number, string> = {
                  1: "支付宝",
                  2: "微信",
                  3: "商福通",
                  4: "商福通渠道支付宝",
                  5: "商福通渠道微信",
                }
                return (
                  <div>
                    {methodMap[row.original.method as number] || "未知"}
                  </div>
                )
              },
            },
            { header: "渠道订单号", accessorKey: "outer_no" },
          ]}
        />
      </Suspense>
    </Page>
  )
}
