import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { supabase } from "@/integrations/supabase/client";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";

const couponSchema = z.object({
  name: z.string().trim().min(1, "请输入优惠券名称").max(100, "名称不能超过100字符"),
  code: z.string().trim().min(4, "券码至少4个字符").max(20, "券码不能超过20字符")
    .regex(/^[A-Z0-9]+$/, "券码只能包含大写字母和数字"),
  type: z.enum(["amount", "percentage"], { required_error: "请选择优惠券类型" }),
  discount_value: z.number().positive("折扣值必须大于0"),
  min_purchase_amount: z.number().min(0, "最低消费金额不能为负数").default(0),
  max_discount_amount: z.number().positive().optional(),
  total_quantity: z.number().int().positive("发放数量必须为正整数"),
  per_user_limit: z.number().int().positive("每人限领必须为正整数").default(1),
  start_date: z.date({ required_error: "请选择开始日期" }),
  end_date: z.date({ required_error: "请选择结束日期" }),
  status: z.enum(["active", "inactive"]).default("active"),
  scope: z.enum(["all", "products", "categories"]).default("all"),
  description: z.string().max(500, "描述不能超过500字符").optional(),
}).refine((data) => data.end_date > data.start_date, {
  message: "结束日期必须晚于开始日期",
  path: ["end_date"],
}).refine((data) => {
  if (data.type === "percentage") {
    return data.discount_value <= 100;
  }
  return true;
}, {
  message: "折扣率不能超过100%",
  path: ["discount_value"],
});

type CouponFormValues = z.infer<typeof couponSchema>;

interface CouponDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  couponId?: string;
  onSuccess?: () => void;
}

export function CouponDialog({ isOpen, onOpenChange, couponId, onSuccess }: CouponDialogProps) {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const form = useForm<CouponFormValues>({
    resolver: zodResolver(couponSchema),
    defaultValues: {
      name: "",
      code: "",
      type: "amount",
      discount_value: 0,
      min_purchase_amount: 0,
      total_quantity: 100,
      per_user_limit: 1,
      status: "active",
      scope: "all",
      description: "",
    },
  });

  useEffect(() => {
    if (isOpen && couponId) {
      fetchCouponData();
    } else if (isOpen) {
      form.reset();
    }
  }, [isOpen, couponId]);

  const fetchCouponData = async () => {
    try {
      const { data, error } = await supabase
        .from("coupons")
        .select("*")
        .eq("id", couponId)
        .single();

      if (error) throw error;

      if (data) {
        form.reset({
          name: data.name,
          code: data.code,
          type: data.type as "amount" | "percentage",
          discount_value: parseFloat(String(data.discount_value)),
          min_purchase_amount: parseFloat(String(data.min_purchase_amount || 0)),
          max_discount_amount: data.max_discount_amount ? parseFloat(String(data.max_discount_amount)) : undefined,
          total_quantity: data.total_quantity,
          per_user_limit: data.per_user_limit,
          start_date: new Date(data.start_date),
          end_date: new Date(data.end_date),
          status: data.status as "active" | "inactive",
          scope: data.scope as "all" | "products" | "categories",
          description: data.description || "",
        });
      }
    } catch (error) {
      console.error("Error fetching coupon:", error);
      toast({
        title: "错误",
        description: "获取优惠券信息失败",
        variant: "destructive",
      });
    }
  };

  const onSubmit = async (values: CouponFormValues) => {
    try {
      setLoading(true);

      const couponData = {
        name: values.name,
        code: values.code.toUpperCase(),
        type: values.type,
        discount_value: values.discount_value,
        min_purchase_amount: values.min_purchase_amount,
        max_discount_amount: values.max_discount_amount,
        total_quantity: values.total_quantity,
        per_user_limit: values.per_user_limit,
        start_date: values.start_date.toISOString(),
        end_date: values.end_date.toISOString(),
        status: values.status,
        scope: values.scope,
        description: values.description,
      };

      if (couponId) {
        const { error } = await supabase
          .from("coupons")
          .update(couponData)
          .eq("id", couponId);

        if (error) throw error;

        toast({
          title: "成功",
          description: "优惠券已更新",
        });
      } else {
        const { error } = await supabase
          .from("coupons")
          .insert(couponData);

        if (error) throw error;

        toast({
          title: "成功",
          description: "优惠券已创建",
        });
      }

      onSuccess?.();
      onOpenChange(false);
      form.reset();
    } catch (error: any) {
      console.error("Error saving coupon:", error);
      toast({
        title: "错误",
        description: error.message || "保存优惠券失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{couponId ? "编辑优惠券" : "创建优惠券"}</DialogTitle>
          <DialogDescription>
            设置优惠券的基本信息和使用规则
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>优惠券名称 *</FormLabel>
                    <FormControl>
                      <Input placeholder="例如：新人专享券" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="code"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>券码 *</FormLabel>
                    <FormControl>
                      <Input 
                        placeholder="例如：NEW2024" 
                        {...field} 
                        onChange={(e) => field.onChange(e.target.value.toUpperCase())}
                      />
                    </FormControl>
                    <FormDescription>只能包含大写字母和数字</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="type"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>优惠类型 *</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="选择优惠类型" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="amount">金额券</SelectItem>
                        <SelectItem value="percentage">折扣券</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="discount_value"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>折扣值 *</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        step="0.01"
                        placeholder={form.watch("type") === "amount" ? "例如：50" : "例如：10"}
                        {...field}
                        onChange={(e) => field.onChange(parseFloat(e.target.value))}
                      />
                    </FormControl>
                    <FormDescription>
                      {form.watch("type") === "amount" ? "减免金额（元）" : "折扣比例（%）"}
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="min_purchase_amount"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>最低消费金额</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        step="0.01"
                        placeholder="0"
                        {...field}
                        onChange={(e) => field.onChange(parseFloat(e.target.value))}
                      />
                    </FormControl>
                    <FormDescription>满足此金额才可使用</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="max_discount_amount"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>最高优惠金额</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        step="0.01"
                        placeholder="不限制"
                        {...field}
                        value={field.value || ""}
                        onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : undefined)}
                      />
                    </FormControl>
                    <FormDescription>折扣券最高减免金额</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="total_quantity"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>发放数量 *</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        placeholder="100"
                        {...field}
                        onChange={(e) => field.onChange(parseInt(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="per_user_limit"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>每人限领 *</FormLabel>
                    <FormControl>
                      <Input 
                        type="number" 
                        placeholder="1"
                        {...field}
                        onChange={(e) => field.onChange(parseInt(e.target.value))}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="start_date"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>开始日期 *</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <FormControl>
                          <Button
                            variant="outline"
                            className={cn(
                              "pl-3 text-left font-normal",
                              !field.value && "text-muted-foreground"
                            )}
                          >
                            {field.value ? (
                              format(field.value, "PPP")
                            ) : (
                              <span>选择日期</span>
                            )}
                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                          </Button>
                        </FormControl>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0" align="start">
                        <Calendar
                          mode="single"
                          selected={field.value}
                          onSelect={field.onChange}
                          disabled={(date) => date < new Date(new Date().setHours(0, 0, 0, 0))}
                          initialFocus
                        />
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="end_date"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>结束日期 *</FormLabel>
                    <Popover>
                      <PopoverTrigger asChild>
                        <FormControl>
                          <Button
                            variant="outline"
                            className={cn(
                              "pl-3 text-left font-normal",
                              !field.value && "text-muted-foreground"
                            )}
                          >
                            {field.value ? (
                              format(field.value, "PPP")
                            ) : (
                              <span>选择日期</span>
                            )}
                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                          </Button>
                        </FormControl>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0" align="start">
                        <Calendar
                          mode="single"
                          selected={field.value}
                          onSelect={field.onChange}
                          disabled={(date) => date < new Date(new Date().setHours(0, 0, 0, 0))}
                          initialFocus
                        />
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>状态</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="active">启用</SelectItem>
                        <SelectItem value="inactive">禁用</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="scope"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>适用范围</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="all">全部商品</SelectItem>
                        <SelectItem value="products">指定商品</SelectItem>
                        <SelectItem value="categories">指定分类</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>券描述</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="优惠券的详细说明..."
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                取消
              </Button>
              <Button type="submit" disabled={loading}>
                {loading ? "保存中..." : couponId ? "更新" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}