"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { bindAdmin, getPageUserPage } from "@/actions/user"
import { Auth } from "@/components/auth"
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 { useFetch } from "@/hooks/data"
import { ScopeUserWriteBind } from "@/lib/scopes"
import type { User } from "@/models/user"

interface FilterValues {
  phone?: string
}

const filterSchema = z.object({
  phone: z.string().optional(),
})

type FormValues = z.infer<typeof filterSchema>

export default function UserPage() {
  const [filters, setFilters] = useState<FilterValues>({})
  const [loading, setLoading] = useState(false)

  const { control, handleSubmit, reset } = useForm<FormValues>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      phone: "",
    },
  })

  const fetchUsers = useCallback(
    (page: number, size: number) => getPageUserPage({ page, size, ...filters }),
    [filters],
  )

  const table = useDataTable<User>(fetchUsers)
  const bind = useFetch(table, (id: number) => bindAdmin({ id }), {
    done: "用户已认领",
    fail: "用户认领失败",
  })

  const onFilter = handleSubmit(data => {
    const result: FilterValues = {}
    if (data.phone) result.phone = data.phone
    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>
            )}
          />
        </div>

        <FieldGroup className="flex-row justify-start mt-4 gap-2">
          <Button type="submit">搜索</Button>
          <Button
            type="button"
            variant="outline"
            onClick={() => {
              reset()
              setFilters({})
              setLoading(false)
            }}
          >
            重置
          </Button>
        </FieldGroup>
      </form>

      <Suspense>
        <DataTable<User>
          {...table}
          status={loading ? "load" : "done"}
          columns={[
            { header: "账号", accessorKey: "username" },
            { header: "手机", accessorKey: "phone" },
            { header: "邮箱", accessorKey: "email" },
            { header: "姓名", accessorKey: "name" },
            {
              header: "余额",
              accessorKey: "balance",
              cell: ({ row }) => {
                const balance = Number(row.original.balance) || 0
                return (
                  <span
                    className={
                      balance > 0 ? "text-green-500" : "text-orange-500"
                    }
                  >
                    ￥{balance.toFixed(2)}
                  </span>
                )
              },
            },
            {
              header: "实名状态",
              accessorKey: "id_type",
              cell: ({ row }) => (
                <Badge
                  variant={row.original.id_type === 1 ? "default" : "secondary"}
                  className={
                    row.original.id_type === 1
                      ? "bg-green-100 text-green-800"
                      : "bg-gray-100 text-gray-800"
                  }
                >
                  {row.original.id_type === 1 ? "已认证" : "未认证"}
                </Badge>
              ),
            },
            {
              header: "客户来源",
              accessorKey: "source",
              cell: ({ row }) => {
                const sourceMap: Record<number, string> = {
                  0: "官网注册",
                  1: "管理员添加",
                  2: "代理商注册",
                  3: "代理商添加",
                }
                return sourceMap[row.original.source] ?? "未知"
              },
            },
            {
              header: "账号状态",
              accessorKey: "status",
              cell: ({ row }) => (row.original.status === 1 ? "正常" : "禁用"),
            },
            { header: "联系方式", accessorKey: "contact_wechat" },
            {
              header: "最后登录时间",
              accessorKey: "last_login",
              cell: ({ row }) =>
                row.original.last_login
                  ? format(
                      new Date(row.original.last_login),
                      "yyyy-MM-dd HH:mm",
                    )
                  : "",
            },
            {
              header: "最后登录IP",
              accessorKey: "last_login_ip",
              cell: ({ row }) => row.original.last_login_ip || "",
            },
            {
              header: "创建时间",
              accessorKey: "created_at",
              cell: ({ row }) =>
                format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
            },
            {
              id: "action",
              meta: { pin: "right" },
              header: "操作",
              cell: ctx => (
                <Auth scope={ScopeUserWriteBind}>
                  <Button
                    size="sm"
                    onClick={() => bind(ctx.row.original.id)}
                    disabled={!!ctx.row.original.admin_id}
                  >
                    {ctx.row.original.admin_id ? "已认领" : "认领"}
                  </Button>
                </Auth>
              ),
            },
          ]}
        />
      </Suspense>
    </div>
  )
}
