import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { 
  ArrowLeft, 
  ShoppingCart, 
  CreditCard, 
  Truck, 
  Shield,
  MapPin,
  Clock,
  Ticket,
  ChevronRight
} from "lucide-react";
import { useCart } from "@/contexts/CartContext";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";

const shippingSchema = z.object({
  name: z.string().trim().min(2, "姓名至少2个字符").max(50, "姓名不能超过50个字符"),
  phone: z.string().trim().regex(/^1[3-9]\d{9}$/, "请输入有效的手机号码"),
  address: z.string().trim().min(5, "地址至少5个字符").max(200, "地址不能超过200个字符"),
  city: z.string().trim().max(50, "城市不能超过50个字符").optional().or(z.literal("")),
  postalCode: z.string().trim().regex(/^\d{6}$/, "请输入6位邮政编码").optional().or(z.literal("")),
});
const notesSchema = z.string().max(500, "备注不能超过500个字符").optional().or(z.literal(""));

interface ShippingAddress {
  name: string;
  phone: string;
  address: string;
  city: string;
  postalCode: string;
}

interface UserCoupon {
  id: string;
  coupon_id: string;
  coupons: {
    id: string;
    code: string;
    name: string;
    description: string;
    type: string;
    discount_value: number;
    min_purchase_amount: number | null;
    max_discount_amount: number | null;
    scope: string;
  };
}

export default function CheckoutPage() {
  const { items, total, itemCount, clearCart } = useCart();
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [isLoading, setIsLoading] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState("alipay");
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [shippingAddress, setShippingAddress] = useState<ShippingAddress>({
    name: "",
    phone: "",
    address: "",
    city: "",
    postalCode: ""
  });
  const [notes, setNotes] = useState("");
  const [availableCoupons, setAvailableCoupons] = useState<UserCoupon[]>([]);
  const [selectedCoupon, setSelectedCoupon] = useState<UserCoupon | null>(null);
  const [showCoupons, setShowCoupons] = useState(false);

  useEffect(() => {
    if (user) {
      fetchAvailableCoupons();
    }
  }, [user]);

  const fetchAvailableCoupons = async () => {
    if (!user) return;

    const { data, error } = await supabase
      .from("user_coupons")
      .select(`
        id,
        coupon_id,
        coupons (
          id,
          code,
          name,
          description,
          type,
          discount_value,
          min_purchase_amount,
          max_discount_amount,
          scope,
          end_date
        )
      `)
      .eq("user_id", user.id)
      .eq("status", "unused")
      .gte("coupons.end_date", new Date().toISOString());

    if (!error && data) {
      const validCoupons = data.filter(uc => {
        const coupon = uc.coupons as any;
        if (!coupon.min_purchase_amount) return true;
        return total >= coupon.min_purchase_amount;
      }) as UserCoupon[];
      setAvailableCoupons(validCoupons);
    }
  };

  const calculateDiscount = () => {
    if (!selectedCoupon) return 0;
    const coupon = selectedCoupon.coupons;
    
    if (coupon.type === "percentage") {
      const discount = total * (coupon.discount_value / 100);
      return coupon.max_discount_amount 
        ? Math.min(discount, coupon.max_discount_amount)
        : discount;
    } else {
      return coupon.discount_value;
    }
  };

  const discountAmount = calculateDiscount();
  const shippingFee = total >= 199 ? 0 : 15;
  const finalTotal = total + shippingFee - discountAmount;

  const handlePlaceOrder = async () => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录才能下单",
        variant: "destructive"
      });
      navigate("/auth");
      return;
    }

    if (!agreedToTerms) {
      toast({
        title: "请同意服务条款",
        description: "您需要同意服务条款才能下单",
        variant: "destructive"
      });
      return;
    }

    const shippingResult = shippingSchema.safeParse(shippingAddress);
    if (!shippingResult.success) {
      toast({
        title: "请检查收货信息",
        description: shippingResult.error.errors[0].message,
        variant: "destructive",
      });
      return;
    }
    const notesResult = notesSchema.safeParse(notes);
    if (!notesResult.success) {
      toast({
        title: "备注过长",
        description: notesResult.error.errors[0].message,
        variant: "destructive",
      });
      return;
    }

    setIsLoading(true);

    try {
      // 生成订单号
      const orderNumber = `ORD${Date.now()}`;
      
      // 构建收货地址字符串
      const fullAddress = `${shippingAddress.name}, ${shippingAddress.phone}, ${shippingAddress.address}, ${shippingAddress.city} ${shippingAddress.postalCode}`;

      // 创建订单
      const { data: orderData, error: orderError } = await supabase
        .from("orders")
        .insert({
          order_number: orderNumber,
          user_id: user.id,
          total_amount: finalTotal,
          status: "pending",
          shipping_address: fullAddress,
          notes: notes || null,
        })
        .select()
        .single();

      if (orderError) throw orderError;

      // 如果使用了优惠券，更新优惠券状态
      if (selectedCoupon) {
        const { error: couponError } = await supabase
          .from("user_coupons")
          .update({
            status: "used",
            used_at: new Date().toISOString(),
            order_id: orderData.id
          })
          .eq("id", selectedCoupon.id);

        if (couponError) {
          console.error("Failed to update coupon:", couponError);
        }
      }

      // 创建订单项
      const orderItems = items.map(item => ({
        order_id: orderData.id,
        product_id: item.id,
        quantity: item.quantity,
        unit_price: item.price,
      }));

      const { error: itemsError } = await supabase
        .from("order_items")
        .insert(orderItems);

      if (itemsError) throw itemsError;

      toast({
        title: "订单创建成功！",
        description: `订单号：${orderNumber}，我们会尽快为您处理`,
      });

      // 清空购物车
      clearCart();

      // 跳转到首页
      setTimeout(() => {
        navigate("/");
        toast({
          title: "下单完成",
          description: "感谢您的购买，您可以在个人中心查看订单状态！",
        });
      }, 1500);

    } catch (error) {
      console.error("Order creation error:", error);
      toast({
        title: "订单创建失败",
        description: "请稍后重试或联系客服",
        variant: "destructive"
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (itemCount === 0) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <ShoppingCart className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-foreground mb-2">购物车为空</h2>
          <p className="text-muted-foreground mb-4">您还没有添加任何商品到购物车</p>
          <Button onClick={() => navigate("/")} className="flex items-center space-x-2">
            <ArrowLeft className="h-4 w-4" />
            <span>返回购物</span>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted">
      <div className="container mx-auto px-4 py-8 max-w-6xl">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button 
                onClick={() => navigate("/")} 
                variant="outline" 
                size="sm"
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="h-4 w-4" />
                <span>返回购物</span>
              </Button>
              <div>
                <h1 className="text-3xl font-bold text-foreground">订单结算</h1>
                <p className="text-muted-foreground">确认您的订单信息并完成支付</p>
              </div>
            </div>
            <Badge variant="secondary" className="text-lg px-4 py-2">
              {itemCount} 件商品
            </Badge>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧：订单信息 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 收货地址 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <MapPin className="h-5 w-5 mr-2" />
                  收货地址
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">收货人 *</Label>
                    <Input
                      id="name"
                      maxLength={50}
                      value={shippingAddress.name}
                      onChange={(e) => setShippingAddress({...shippingAddress, name: e.target.value})}
                      placeholder="请输入收货人姓名"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone">联系电话 *</Label>
                    <Input
                      id="phone"
                      maxLength={11}
                      inputMode="numeric"
                      value={shippingAddress.phone}
                      onChange={(e) => setShippingAddress({...shippingAddress, phone: e.target.value})}
                      placeholder="请输入手机号码"
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="address">详细地址 *</Label>
                  <Input
                    id="address"
                    maxLength={200}
                    value={shippingAddress.address}
                    onChange={(e) => setShippingAddress({...shippingAddress, address: e.target.value})}
                    placeholder="请输入详细地址"
                  />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="city">城市</Label>
                    <Input
                      id="city"
                      maxLength={50}
                      value={shippingAddress.city}
                      onChange={(e) => setShippingAddress({...shippingAddress, city: e.target.value})}
                      placeholder="请输入城市"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="postalCode">邮政编码</Label>
                    <Input
                      id="postalCode"
                      maxLength={6}
                      inputMode="numeric"
                      value={shippingAddress.postalCode}
                      onChange={(e) => setShippingAddress({...shippingAddress, postalCode: e.target.value})}
                      placeholder="请输入邮政编码"
                    />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 配送方式 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <Truck className="h-5 w-5 mr-2" />
                  配送方式
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center justify-between p-3 border border-border rounded-lg bg-primary/5">
                    <div className="flex items-center space-x-3">
                      <Clock className="h-5 w-5 text-primary" />
                      <div>
                        <p className="font-medium">标准配送</p>
                        <p className="text-sm text-muted-foreground">3-5个工作日送达</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-medium">
                        {shippingFee === 0 ? "免费" : `¥${shippingFee}`}
                      </p>
                      {total >= 199 && (
                        <Badge variant="secondary" className="text-xs">满199免运费</Badge>
                      )}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 支付方式 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <CreditCard className="h-5 w-5 mr-2" />
                  支付方式
                </CardTitle>
              </CardHeader>
              <CardContent>
                <RadioGroup value={paymentMethod} onValueChange={setPaymentMethod}>
                  <div className="flex items-center space-x-2 p-3 border border-border rounded-lg">
                    <RadioGroupItem value="alipay" id="alipay" />
                    <Label htmlFor="alipay" className="flex-1 cursor-pointer">
                      <div className="flex items-center justify-between">
                        <span>支付宝</span>
                        <Badge variant="outline">推荐</Badge>
                      </div>
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2 p-3 border border-border rounded-lg">
                    <RadioGroupItem value="wechat" id="wechat" />
                    <Label htmlFor="wechat" className="flex-1 cursor-pointer">微信支付</Label>
                  </div>
                  <div className="flex items-center space-x-2 p-3 border border-border rounded-lg">
                    <RadioGroupItem value="unionpay" id="unionpay" />
                    <Label htmlFor="unionpay" className="flex-1 cursor-pointer">银联支付</Label>
                  </div>
                </RadioGroup>
              </CardContent>
            </Card>

            {/* 优惠券选择 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  <div className="flex items-center">
                    <Ticket className="h-5 w-5 mr-2" />
                    优惠券
                  </div>
                  {availableCoupons.length > 0 && (
                    <Badge variant="secondary">{availableCoupons.length} 张可用</Badge>
                  )}
                </CardTitle>
              </CardHeader>
              <CardContent>
                {availableCoupons.length === 0 ? (
                  <p className="text-sm text-muted-foreground">暂无可用优惠券</p>
                ) : (
                  <div className="space-y-2">
                    <Button
                      variant="outline"
                      className="w-full justify-between"
                      onClick={() => setShowCoupons(!showCoupons)}
                    >
                      <span>
                        {selectedCoupon 
                          ? `已选择: ${selectedCoupon.coupons.name}`
                          : "选择优惠券"}
                      </span>
                      <ChevronRight className={`h-4 w-4 transition-transform ${showCoupons ? 'rotate-90' : ''}`} />
                    </Button>
                    
                    {showCoupons && (
                      <ScrollArea className="max-h-[300px] border border-border rounded-lg p-2">
                        <div className="space-y-2">
                          {availableCoupons.map((userCoupon) => {
                            const coupon = userCoupon.coupons;
                            const isSelected = selectedCoupon?.id === userCoupon.id;
                            return (
                              <div
                                key={userCoupon.id}
                                onClick={() => {
                                  setSelectedCoupon(isSelected ? null : userCoupon);
                                  setShowCoupons(false);
                                }}
                                className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                                  isSelected 
                                    ? 'border-primary bg-primary/5' 
                                    : 'border-border hover:border-primary/50'
                                }`}
                              >
                                <div className="flex items-start justify-between">
                                  <div className="flex-1">
                                    <div className="flex items-center space-x-2 mb-1">
                                      <span className="font-medium">{coupon.name}</span>
                                      <Badge variant="secondary" className="text-xs">
                                        {coupon.type === 'percentage' 
                                          ? `${coupon.discount_value}%` 
                                          : `¥${coupon.discount_value}`}
                                      </Badge>
                                    </div>
                                    {coupon.description && (
                                      <p className="text-xs text-muted-foreground">{coupon.description}</p>
                                    )}
                                    {coupon.min_purchase_amount && (
                                      <p className="text-xs text-muted-foreground mt-1">
                                        满 ¥{coupon.min_purchase_amount} 可用
                                      </p>
                                    )}
                                  </div>
                                  {isSelected && (
                                    <Badge className="ml-2">已选择</Badge>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </ScrollArea>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 订单备注 */}
            <Card>
              <CardHeader>
                <CardTitle>订单备注</CardTitle>
              </CardHeader>
              <CardContent>
                <Textarea
                  value={notes}
                  maxLength={500}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="如有特殊要求，请在此填写..."
                  className="min-h-[80px]"
                />
              </CardContent>
            </Card>
          </div>

          {/* 右侧：订单摘要 */}
          <div className="lg:col-span-1">
            <Card className="sticky top-4">
              <CardHeader>
                <CardTitle className="flex items-center">
                  <ShoppingCart className="h-5 w-5 mr-2" />
                  订单摘要
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* 商品列表 */}
                <div className="space-y-3 max-h-60 overflow-y-auto">
                  {items.map((item) => (
                    <div key={item.id} className="flex items-center space-x-3 p-2 border border-border rounded-lg">
                      <div className="w-12 h-12 bg-muted rounded-md overflow-hidden flex-shrink-0">
                        {item.image_url ? (
                          <img
                            src={item.image_url}
                            alt={item.name}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <ShoppingCart className="h-4 w-4 text-muted-foreground" />
                          </div>
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="text-sm font-medium truncate">{item.name}</h4>
                        <div className="flex items-center justify-between text-sm text-muted-foreground">
                          <span>¥{(item.price || 0).toFixed(2)} × {item.quantity}</span>
                          <span className="font-medium text-primary">
                            ¥{((item.price || 0) * item.quantity).toFixed(2)}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                <Separator />

                {/* 费用明细 */}
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span>商品总额</span>
                    <span>¥{(total || 0).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>配送费</span>
                    <span>{shippingFee === 0 ? "免费" : `¥${shippingFee.toFixed(2)}`}</span>
                  </div>
                  {discountAmount > 0 && (
                    <div className="flex justify-between text-sm">
                      <span>优惠券减免</span>
                      <span className="text-green-600">-¥{discountAmount.toFixed(2)}</span>
                    </div>
                  )}
                  <Separator />
                  <div className="flex justify-between text-lg font-bold">
                    <span>总计</span>
                    <span className="text-primary">¥{finalTotal.toFixed(2)}</span>
                  </div>
                </div>

                <Separator />

                {/* 服务保障 */}
                <div className="space-y-2">
                  <div className="flex items-center text-sm text-muted-foreground">
                    <Shield className="h-4 w-4 mr-2 text-green-500" />
                    <span>7天无理由退换货</span>
                  </div>
                  <div className="flex items-center text-sm text-muted-foreground">
                    <Shield className="h-4 w-4 mr-2 text-green-500" />
                    <span>正品保证</span>
                  </div>
                </div>

                <Separator />

                {/* 同意条款 */}
                <div className="flex items-start space-x-2">
                  <Checkbox
                    id="terms"
                    checked={agreedToTerms}
                    onCheckedChange={(checked) => setAgreedToTerms(checked as boolean)}
                  />
                  <Label htmlFor="terms" className="text-sm text-muted-foreground cursor-pointer">
                    我已阅读并同意 <span className="text-primary underline">服务条款</span> 和 <span className="text-primary underline">隐私政策</span>
                  </Label>
                </div>

                {/* 提交订单按钮 */}
                <Button
                  onClick={handlePlaceOrder}
                  className="w-full"
                  size="lg"
                  disabled={isLoading || !agreedToTerms}
                >
                  {isLoading ? "处理中..." : `立即支付 ¥${finalTotal.toFixed(2)}`}
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}