import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
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, Save, ArrowLeft } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

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(["fixed", "percentage"], { required_error: "请选择优惠券类型" }),
  discount_value: z.number().min(0.01, "折扣值必须大于0"),
  min_purchase_amount: z.number().min(0, "最低消费金额不能为负数").default(0),
  max_discount_amount: z.number().positive().optional().nullable(),
  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", "product", "category", "brand"]).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 CouponEditPageProps {
  embedded?: boolean;
  couponId?: string | null;
}

export default function CouponEditPage({ embedded = false, couponId: propCouponId }: CouponEditPageProps = {}) {
  const navigate = useNavigate();
  const id = propCouponId;
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const form = useForm<CouponFormValues>({
    resolver: zodResolver(couponSchema),
    defaultValues: {
      name: "",
      code: "",
      type: "fixed",
      discount_value: 10,
      min_purchase_amount: 0,
      total_quantity: 100,
      per_user_limit: 1,
      start_date: new Date(),
      end_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后
      status: "active",
      scope: "all",
      description: "",
    },
  });

  useEffect(() => {
    if (id && id !== "new") {
      fetchCouponData();
    } else {
      setLoading(false);
    }
  }, [id]);

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

      if (error) throw error;

      if (data) {
        form.reset({
          name: data.name,
          code: data.code,
          type: data.type as "fixed" | "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 ?? 1,
          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" | "product" | "category" | "brand",
          description: data.description || "",
        });
      }
    } catch (error) {
      console.error("Error fetching coupon:", error);
      toast({
        title: "错误",
        description: "获取优惠券信息失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const onSubmit = async (values: CouponFormValues) => {
    try {
      setSaving(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 (id && id !== "new") {
        const { error } = await supabase
          .from("coupons")
          .update(couponData)
          .eq("id", id);

        if (error) throw error;

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

        if (error) throw error;

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

      navigate("/admin?tab=marketing");
    } catch (error: any) {
      console.error("Error saving coupon:", error);
      toast({
        title: "错误",
        description: error.message || "保存优惠券失败",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* 面包屑导航 */}
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink
              onClick={() => navigate("/admin")}
              className="cursor-pointer"
            >
              管理后台
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbLink
              onClick={() => navigate("/admin?tab=marketing")}
              className="cursor-pointer"
            >
              营销管理
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>
              {id === "new" ? "创建优惠券" : "编辑优惠券"}
            </BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      {/* 页面标题和操作按钮 */}
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">
          {id === "new" ? "创建优惠券" : "编辑优惠券"}
        </h1>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => navigate("/admin?tab=marketing")}
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <Button onClick={form.handleSubmit(onSubmit)} disabled={saving}>
            <Save className="w-4 h-4 mr-2" />
            {saving ? "保存中..." : "保存"}
          </Button>
        </div>
      </div>

      {/* 表单内容 */}
      <Card>
        <CardHeader>
          <CardTitle>基本信息</CardTitle>
          <CardDescription>设置优惠券的基本信息和使用规则</CardDescription>
        </CardHeader>
        <CardContent>
          <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} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择优惠类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="fixed">金额券</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") === "fixed" ? "例如：50" : "例如：10"}
                          {...field}
                          onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                        />
                      </FormControl>
                      <FormDescription>
                        {form.watch("type") === "fixed" ? "减免金额（元）" : "折扣比例（%）"}
                      </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, "yyyy-MM-dd")
                              ) : (
                                <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, "yyyy-MM-dd")
                              ) : (
                                <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} value={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} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="all">全场通用</SelectItem>
                          <SelectItem value="product">指定商品</SelectItem>
                          <SelectItem value="category">指定分类</SelectItem>
                          <SelectItem value="brand">指定品牌</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>优惠券描述</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="输入优惠券的使用说明和注意事项"
                        rows={4}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}
