import { zodResolver } from "@hookform/resolvers/zod"
import { Plus } from "lucide-react"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createCoupon } from "@/actions/coupon"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

const schema = z.object({
  code: z.string().min(1, "请输入优惠券名称"),
  amount: z.string().min(1, "请输入优惠券金额"),
  remark: z.string().optional(),
  min_amount: z.string().optional(),
  expire_at: z.string().optional(),
})

export function CreateDiscount(props: { onSuccess?: () => void }) {
  const [open, setOpen] = useState(false)

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      code: "",
      remark: "",
      amount: "0",
      min_amount: "0",
      expire_at: "",
    },
    mode: "onChange",
  })

  const { control, handleSubmit, reset } = form

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const payload = {
        code: data.code,
        amount: Number(data.amount),
        remark: data?.remark,
        min_amount: Number(data?.min_amount),
        expire_at: data?.expire_at ? new Date(data.expire_at) : undefined,
      }
      const resp = await createCoupon(payload)
      if (resp.success) {
        reset()
        toast.success("优惠券创建成功")
        props.onSuccess?.()
        setOpen(false)
      } else {
        toast.error(resp.message)
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : error
      toast.error(`接口请求错误: ${message}`)
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={newOpen => {
        setOpen(newOpen)
        if (!newOpen) {
          reset()
        }
      }}
    >
      <DialogTrigger asChild>
        <Button>
          <Plus />
          创建优惠券
        </Button>
      </DialogTrigger>

      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>创建优惠券</DialogTitle>
        </DialogHeader>

        <form id="discount-create" onSubmit={handleSubmit(onSubmit)}>
          <FieldGroup>
            <Controller
              control={control}
              name="code"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-28 pt-2">名称:</FieldLabel>
                  <div className="flex-1">
                    <Input {...field} />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />

            <Controller
              control={control}
              name="remark"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-28 pt-2">备注:</FieldLabel>
                  <div className="flex-1">
                    <Input {...field} />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />

            <Controller
              control={control}
              name="amount"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-28 pt-2">金额:</FieldLabel>
                  <div className="flex-1">
                    <Input
                      type="number"
                      min={0}
                      step={5}
                      {...field}
                      onChange={e => {
                        const value = e.target.value
                        if (value === "" || parseFloat(value) >= 0) {
                          field.onChange(value)
                        }
                      }}
                    />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />
            <Controller
              control={control}
              name="min_amount"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-28 pt-2">最低消费:</FieldLabel>
                  <div className="flex-1">
                    <Input
                      type="number"
                      min={0}
                      step={5}
                      {...field}
                      onChange={e => {
                        const value = e.target.value
                        if (value === "" || parseFloat(value) >= 0) {
                          field.onChange(value)
                        }
                      }}
                    />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />

            <Controller
              control={control}
              name="expire_at"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-30 pt-2">过期时间:</FieldLabel>
                  <Input
                    type="date"
                    min={new Date().toISOString().split("T")[0]}
                    {...field}
                  />
                  <div className="flex-1">
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />
          </FieldGroup>
        </form>

        <DialogFooter>
          <DialogClose asChild>
            <Button variant="ghost">取消</Button>
          </DialogClose>
          <Button type="submit" form="discount-create">
            创建
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
