import { useState, useEffect } from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
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 { 
  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 { useToast } from "@/hooks/use-toast";

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

interface CheckoutDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

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 function CheckoutDialog({ open, onOpenChange }: CheckoutDialogProps) {
  const { items, total, itemCount, clearCart } = useCart();
  const { user } = useAuth();
  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 (open && user) {
      fetchAvailableCoupons();
    }
  }, [open, 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"
      });
      return;
    }

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

    if (!shippingAddress.name || !shippingAddress.phone || !shippingAddress.address) {
      toast({
        title: "请填写完整的收货地址",
        description: "收货人、电话和地址为必填项",
        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();

      // 关闭弹窗
      onOpenChange(false);

      // 显示完成提示
      setTimeout(() => {
        toast({
          title: "下单完成",
          description: "感谢您的购买，您可以在个人中心查看订单状态！",
        });
      }, 500);

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[1400px] max-h-[95vh] p-0 overflow-hidden">
        <div className="grid grid-cols-12 gap-0 h-full bg-background">
          {/* 左侧：订单信息表单 */}
          <div className="col-span-7 overflow-y-auto max-h-[95vh]">
            <ScrollArea className="h-full">
              <div className="p-8 space-y-6">
                {/* 标题 */}
                <div>
                  <h2 className="text-2xl font-bold text-foreground mb-2">订单结算</h2>
                  <p className="text-muted-foreground">确认您的订单信息并完成支付</p>
                </div>

                {/* 收货地址 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-base">
                      <MapPin className="h-5 w-5 mr-2" />
                      收货地址
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="name">收货人 *</Label>
                        <Input
                          id="name"
                          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"
                          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"
                        value={shippingAddress.address}
                        onChange={(e) => setShippingAddress({...shippingAddress, address: e.target.value})}
                        placeholder="请输入详细地址"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="city">城市</Label>
                        <Input
                          id="city"
                          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"
                          value={shippingAddress.postalCode}
                          onChange={(e) => setShippingAddress({...shippingAddress, postalCode: e.target.value})}
                          placeholder="请输入邮政编码"
                        />
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* 配送方式 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-base">
                      <Truck className="h-5 w-5 mr-2" />
                      配送方式
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <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>
                  </CardContent>
                </Card>

                {/* 支付方式 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center text-base">
                      <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 text-base">
                      <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 className="text-base">订单备注</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Textarea
                      value={notes}
                      onChange={(e) => setNotes(e.target.value)}
                      placeholder="如有特殊要求，请在此填写..."
                      className="min-h-[80px]"
                    />
                  </CardContent>
                </Card>
              </div>
            </ScrollArea>
          </div>

          {/* 右侧：订单摘要 */}
          <div className="col-span-5 bg-muted/30 border-l overflow-y-auto max-h-[95vh]">
            <div className="p-8 space-y-6">
              <div>
                <h3 className="text-lg font-semibold flex items-center mb-4">
                  <ShoppingCart className="h-5 w-5 mr-2" />
                  订单摘要
                  <Badge variant="secondary" className="ml-2">{itemCount} 件</Badge>
                </h3>
              </div>

              {/* 商品列表 */}
              <ScrollArea className="max-h-[300px]">
                <div className="space-y-3">
                  {items.map((item) => (
                    <div key={item.id} className="flex items-center space-x-3 p-3 bg-background border border-border rounded-lg">
                      <div className="w-16 h-16 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 mt-1">
                          <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>
              </ScrollArea>

              <Separator />

              {/* 费用明细 */}
              <div className="space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">商品总额</span>
                  <span className="font-medium">¥{(total || 0).toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">配送费</span>
                  <span className="font-medium">{shippingFee === 0 ? "免费" : `¥${shippingFee.toFixed(2)}`}</span>
                </div>
                {discountAmount > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">优惠券减免</span>
                    <span className="font-medium text-green-600">-¥{discountAmount.toFixed(2)}</span>
                  </div>
                )}
                <Separator />
                <div className="flex justify-between text-xl 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 leading-relaxed">
                  我已阅读并同意 <span className="text-primary underline">服务条款</span> 和 <span className="text-primary underline">隐私政策</span>
                </Label>
              </div>

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