import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { batchUpdateProductSkuDiscount } from "@/actions/product"
import { getAllProductDiscount } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import type { ProductDiscount } from "@/models/product_discount"

const schema = z.object({
  discount_id: z.string().min(1, "请选择折扣"),
})

export function BatchUpdateDiscount(props: {
  productId: number
  onSuccess?: () => void
}) {
  const [open, setOpen] = useState(false)
  const [discounts, setDiscounts] = useState<ProductDiscount[]>([])

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

  useEffect(() => {
    if (open) {
      getAllProductDiscount().then(resp => {
        if (resp.success) {
          setDiscounts(resp.data)
        }
      })
    }
  }, [open])

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const resp = await batchUpdateProductSkuDiscount({
        product_id: props.productId,
        discount_id:
          data.discount_id === "none" ? null : Number(data.discount_id),
      })
      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()
    }
    setOpen(value)
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button variant="outline" disabled={!props.productId}>
          批量配置折扣
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>批量配置折扣</DialogTitle>
        </DialogHeader>

        <form id="sku-batch-discount" onSubmit={form.handleSubmit(onSubmit)}>
          <FieldGroup>
            <Controller
              control={form.control}
              name="discount_id"
              render={({ field, fieldState }) => (
                <Field>
                  <FieldLabel>折扣</FieldLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <SelectTrigger
                      className="w-full"
                      aria-invalid={fieldState.invalid}
                    >
                      <SelectValue placeholder="请选择要应用的折扣" />
                    </SelectTrigger>
                    <SelectContent>
                      {discounts.map(d => (
                        <SelectItem key={d.id} value={String(d.id)}>
                          {d.name}（{d.discount}%）
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {fieldState.invalid && (
                    <FieldError errors={[fieldState.error]} />
                  )}
                </Field>
              )}
            />
          </FieldGroup>
        </form>

        <DialogFooter>
          <DialogClose asChild>
            <Button variant="ghost">取消</Button>
          </DialogClose>
          <Button type="submit" form="sku-batch-discount">
            确认应用
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
