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 { updateProductDiscount } 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"
import type { ProductDiscount } from "@/models/product_discount"

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

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

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

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const resp = await updateProductDiscount({
        id: props.discount.id,
        ...data,
      })
      if (resp.success) {
        toast.success("折扣修改成功")
        props.onSuccess?.()
        setOpen(false)
      } else {
        toast.error(resp.message)
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : error
      toast.error(`接口请求错误: ${message}`)
    }
  }

  const handleOpenChange = (value: boolean) => {
    if (value) {
      form.reset({
        name: props.discount.name,
        discount: String(props.discount.discount),
      })
    }
    setOpen(value)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button size="sm" variant="secondary">
          修改
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>修改折扣</DialogTitle>
        </DialogHeader>

        <form id="discount-update" onSubmit={form.handleSubmit(onSubmit)}>
          <FieldGroup>
            <Controller
              control={form.control}
              name="name"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel htmlFor="discount-update-name">名称</FieldLabel>
                  <Input
                    id="discount-update-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-update-discount">
                    折扣
                  </FieldLabel>
                  <Input
                    id="discount-update-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-update">
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
