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

const schema = z.object({
  name: z.string().min(1, "请输入折扣名称"),
  discount: z.string().min(1, "请输入折扣代码"),
})

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

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      name: "",
      discount: "",
    },
  })

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const resp = await createProductDiscount(data)
      if (resp.success) {
        form.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={setOpen}>
      <DialogTrigger asChild>
        <Button>创建折扣</Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>创建折扣</DialogTitle>
        </DialogHeader>

        <form id="discount-create" onSubmit={form.handleSubmit(onSubmit)}>
          <FieldGroup>
            <Controller
              control={form.control}
              name="name"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel htmlFor="discount-create-name">名称</FieldLabel>
                  <Input
                    id="discount-create-name"
                    {...field}
                    aria-invalid={fieldState.invalid}
                  />
                  {fieldState.invalid && (
                    <FieldError errors={[fieldState.error]} />
                  )}
                </Field>
              )}
            />

            <Controller
              control={form.control}
              name="discount"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel htmlFor="discount-create-discount">
                    代码
                  </FieldLabel>
                  <Input
                    id="discount-create-discount"
                    {...field}
                    aria-invalid={fieldState.invalid}
                  />
                  {fieldState.invalid && (
                    <FieldError errors={[fieldState.error]} />
                  )}
                </Field>
              )}
            />
          </FieldGroup>
        </form>

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