"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CreditCard, Wallet } from "lucide-react"
import { Suspense, useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getPageBill, getSkuList } from "@/actions/bill"
import { DataTable, useDataTable } from "@/components/data-table"
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 { ProductCode } from "@/lib/base"
import type { Billing } from "@/models/billing"

type FilterValues = {
  bill_no?: string
  user_phone?: string
  trade_inner_no?: string
  resource_no?: string
  sku_code?: string
  product_code?: string
  created_at_start?: Date
  created_at_end?: Date
}

type SkuOption = {
  resource_code: string
  resource_name: string
}

const filterSchema = z
  .object({
    phone: z
      .string()
      .optional()
      .transform(val => val?.trim()),
    bill_no: z
      .string()
      .optional()
      .transform(val => val?.trim()),
    resource_no: z.string().optional(),
    inner_no: z.string().optional(),
    created_at_start: z.string().optional(),
    created_at_end: z.string().optional(),
    product_code: z.string().optional(),
    sku_code: 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 BillingPage() {
  const [filters, setFilters] = useState<FilterValues>({})
  const [skuOptions, setSkuOptions] = useState<SkuOption[]>([])
  const [loading, setLoading] = useState(true)
  const [skuProductCode, setSkuProductCode] = useState<ProductCode>(
    ProductCode.All,
  )
  const { control, handleSubmit, reset } = useForm<FilterSchema>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      bill_no: "",
      inner_no: "",
      created_at_start: "",
      created_at_end: "",
      phone: "",
      resource_no: "",
      sku_code: "all",
      product_code: "",
    },
  })

  useEffect(() => {
    setLoading(true)                           
    getSkuList({
      product_code: skuProductCode,
    })
      .then(resp => {
        if (!resp.success) {
          throw new Error(resp.message)
        }
        setSkuOptions(
          resp.data.map(sku => ({
            resource_code: sku.code,
            resource_name: sku.name,
          })),
        )
      })
      .catch(e => {
        console.error("获取套餐类型失败:", e)
        toast.error(
          `获取套餐类型失败：${e instanceof Error ? e.message : String(e)}`,
        )
        setSkuOptions([])
      })
      .finally(() => {
        setLoading(false)
      })
  }, [skuProductCode])

  const table = useDataTable<Billing>((page, size) =>
    getPageBill({ page, size, ...filters }),
  )

  const onFilter = handleSubmit(data => {
    const result: FilterValues = {}
    if (data.phone?.trim()) result.user_phone = data.phone.trim()
    if (data.inner_no?.trim()) result.trade_inner_no = data.inner_no.trim()
    if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
    if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
    if (data.product_code && data.product_code !== ProductCode.All) {
      result.product_code = data.product_code
    }
    if (data.sku_code && data.sku_code !== "all") {
      result.sku_code = data.sku_code
    }
    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 (
    <div className="space-y-3">
      <form onSubmit={onFilter} className="bg-white p-4">
        <div className="flex flex-wrap items-end gap-4">
          <Controller
            name="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="bill_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="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="product_code"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-32 flex-none"
              >
                <FieldLabel>产品类型</FieldLabel>
                <Select
                  value={skuProductCode}
                  onValueChange={value => {
                    setSkuProductCode(value as ProductCode)
                    field.onChange(value)
                  }}
                >
                  <SelectTrigger>
                    <SelectValue
                      placeholder={"请选择"}
                      defaultValue={
                        skuProductCode === ProductCode.All ? "全部" : ""
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ProductCode.All}>全部</SelectItem>
                    <SelectItem value={ProductCode.Short}>短效</SelectItem>
                    <SelectItem value={ProductCode.Long}>长效</SelectItem>
                  </SelectContent>
                </Select>
              </Field>
            )}
          />

          <Controller
            name="sku_code"
            control={control}
            render={({ field, fieldState }) => (
              <Field
                data-invalid={fieldState.invalid}
                className="w-32 flex-none"
              >
                <FieldLabel>套餐类型</FieldLabel>
                <Select
                  value={loading ? undefined : field.value || "all"}
                  onValueChange={field.onChange}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={loading ? "加载中..." : "全部"} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    {skuOptions.map(option => (
                      <SelectItem
                        key={option.resource_code}
                        value={option.resource_code}
                      >
                        {option.resource_name || option.resource_code}
                      </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()
              setSkuProductCode(ProductCode.All)
              setFilters({})
              table.pagination.onPageChange(1)
            }}
          >
            重置
          </Button>
        </FieldGroup>
      </form>

      <Suspense>
        <DataTable<Billing>
          {...table}
          columns={[
            { header: "会员号", accessorFn: row => row.user?.phone || "-" },
            { header: "套餐号", accessorKey: "resource.resource_no" },
            {
              header: "账单详情",
              accessorKey: "info",
              cell: ({ row }) => {
                const bill = row.original

                return (
                  <div className="flex items-center gap-2">
                    <div className="shrink-0">
                      {bill.type === 1 && (
                        <div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>消费</span>
                        </div>
                      )}
                      {bill.type === 2 && (
                        <div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>退款</span>
                        </div>
                      )}
                      {bill.type === 3 && (
                        <div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>充值</span>
                        </div>
                      )}
                    </div>
                    <div className="text-sm">{bill.info}</div>
                  </div>
                )
              },
            },
            {
              header: "应付金额",
              accessorKey: "amount",
              cell: ({ row }) => {
                const amount =
                  typeof row.original.amount === "string"
                    ? parseFloat(row.original.amount)
                    : row.original.amount || 0
                return (
                  <div className="flex gap-1">
                    <span
                      className={
                        amount > 0 ? "text-green-500" : "text-orange-500"
                      }
                    >
                      ￥{amount.toFixed(2)}
                    </span>
                  </div>
                )
              },
            },
            {
              header: "实付金额",
              accessorKey: "actual",
              cell: ({ row }) => {
                const actual =
                  typeof row.original.actual === "string"
                    ? parseFloat(row.original.actual)
                    : row.original.actual || 0
                return (
                  <div className="flex gap-1">
                    <span
                      className={
                        actual > 0 ? "text-green-500" : "text-orange-500"
                      }
                    >
                      ￥{actual.toFixed(2)}
                    </span>
                  </div>
                )
              },
            },
            { header: "账单号", accessorKey: "bill_no" },
            {
              header: "订单号",
              accessorKey: "trade.inner_no",
              cell: ({ row }) => {
                const bill = row.original

                return (
                  <div className="flex items-center gap-2">
                    <div className="shrink-0 w-20">
                      {bill.trade?.acquirer === 1 && (
                        <div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>支付宝</span>
                        </div>
                      )}
                      {bill.trade?.acquirer === 2 && (
                        <div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>微信</span>
                        </div>
                      )}
                      {bill.trade?.acquirer === 3 && (
                        <div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
                          <CreditCard size={16} />
                          <span>银联</span>
                        </div>
                      )}
                      {!bill.trade?.acquirer && (
                        <div className="flex gap-2 items-center bg-red-50 w-full px-2 py-1 rounded-md">
                          <Wallet size={16} />
                          <span>余额</span>
                        </div>
                      )}
                    </div>
                    <div className="text-sm">{bill.trade?.inner_no}</div>
                  </div>
                )
              },
            },
            {
              header: "创建时间",
              accessorKey: "created_at",
              cell: ({ row }) =>
                format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
            },
          ]}
        />
      </Suspense>
    </div>
  )
}
