"use client"
import { useState } from "react"
import { toast } from "sonner"
import { getPagCoupon } from "@/actions/coupon"
import { DataTable, useDataTable } from "@/components/data-table"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import type { Coupon } from "@/models/coupon"

export function IssueCouponForUser(props: {
  userId: number
  userPhone: string
  onSuccess?: () => void
}) {
  const [open, setOpen] = useState(false)

  const table = useDataTable<Coupon>((page, size) =>
    getPagCoupon({ page, size }),
  )

  const handleIssue = async (coupon: Coupon) => {
    // try {
    //   const result = await issueCouponToUser({
    //     user_id: props.userId,
    //     coupon_id: coupon.id,
    //     coupon_name: coupon.name,
    //   })
    //   if (result.success) {
    //     toast.success(`成功发放「${coupon.name}」给用户 ${props.userPhone}`)
    //     props.onSuccess?.()
    //     setOpen(false)
    //   } else {
    //     toast.error(result.message || "发放失败")
    //   }
    // } catch (error) {
    //   const message = error instanceof Error ? error.message : "发放失败"
    //   toast.error(`发放优惠券失败: ${message}`)
    // }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={newOpen => {
        setOpen(newOpen)
        if (newOpen) {
          table.refresh()
        }
      }}
    >
      <DialogTrigger asChild>
        <Button>发放优惠券</Button>
      </DialogTrigger>
      <DialogContent
        className="max-h-[85vh] overflow-y-auto"
        style={{ width: "auto", minWidth: "800px", maxWidth: "90vw" }}
      >
        <DialogHeader>
          <DialogTitle>发放优惠券给 {props.userPhone}</DialogTitle>
        </DialogHeader>
        <DataTable<Coupon>
          {...table}
          columns={[
            { header: "优惠券名称", accessorKey: "name" },
            { header: "优惠券金额", accessorKey: "amount" },
            { header: "最低消费金额", accessorKey: "min_amount" },
            {
              header: "状态",
              accessorKey: "status",
              cell: ({ row }) => {
                const status = row.original.status
                if (status === 0) {
                  return <span className="text-yellow-600">禁用</span>
                }
                if (status === 1) {
                  return <span className="text-green-600">正常</span>
                }
                return <span>-</span>
              },
            },
            {
              id: "action",
              meta: { pin: "right" },
              header: "操作",
              cell: ({ row }) => (
                <Button size="sm" onClick={() => handleIssue(row.original)}>
                  发放
                </Button>
              ),
            },
          ]}
        />
        <DialogFooter>
          <DialogClose asChild>
            <Button variant="ghost">取消</Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
