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 { updateCoupon } 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"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import type { Coupon } from "@/models/coupon"

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(),
  status: z.string().optional(),
})

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

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      code: props.coupon.code || "",
      remark: props.coupon.remark || "",
      amount: String(props.coupon.amount || 0),
      min_amount: String(props.coupon.min_amount || 0),
      expire_at: props.coupon.expire_at
        ? new Date(props.coupon.expire_at).toISOString().split("T")[0]
        : "",
      status: String(props.coupon.status || "0"),
    },
    mode: "onChange",
  })

  const { control, handleSubmit, reset } = form

  const onSubmit = async (data: z.infer<typeof schema>) => {
    try {
      const payload = {
        id: props.coupon.id,
        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,
        status: Number(data.status),
      }
      const resp = await updateCoupon(payload)
      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) {
      reset({
        code: props.coupon.code || "",
        remark: props.coupon.remark || "",
        amount: String(props.coupon.amount || 0),
        min_amount: String(props.coupon.min_amount || 0),
        expire_at: props.coupon.expire_at
          ? new Date(props.coupon.expire_at).toISOString().split("T")[0]
          : "",
        status: String(props.coupon.status || "0"),
      })
    }
    setOpen(value)
  }

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

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

        <form id="coupon-update" 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-28 pt-2">过期时间:</FieldLabel>
                  <div className="flex-1">
                    <Input
                      type="date"
                      min={new Date().toISOString().split("T")[0]}
                      {...field}
                    />
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />

            <Controller
              control={control}
              name="status"
              render={({ field, fieldState }) => (
                <div className="flex items-start gap-4">
                  <FieldLabel className="w-28 pt-2">状态:</FieldLabel>
                  <div className="flex-1">
                    <Select value={field.value} onValueChange={field.onChange}>
                      <SelectTrigger>
                        <SelectValue placeholder="请选择状态" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="0">未使用</SelectItem>
                        <SelectItem value="1">已使用</SelectItem>
                      </SelectContent>
                    </Select>
                    <FieldError>{fieldState.error?.message}</FieldError>
                  </div>
                </div>
              )}
            />
          </FieldGroup>
        </form>

        <DialogFooter>
          <DialogClose asChild>
            <Button variant="ghost">取消</Button>
          </DialogClose>
          <Button type="submit" form="coupon-update">
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
