import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tag, Clock, Gift } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { toast } from "sonner";

interface CouponCardProps {
  coupon: {
    id: string;
    code: string;
    name: string;
    description?: string;
    type: string;
    discount_value: number;
    min_purchase_amount?: number;
    max_discount_amount?: number;
    end_date: string;
    scope: string;
  };
  onReceive?: (couponId: string) => void;
}

export function CouponCard({ coupon, onReceive }: CouponCardProps) {
  const { user } = useAuth();

  const handleReceive = async () => {
    if (!user) {
      toast.error("请先登录");
      return;
    }

    try {
      // 检查用户是否已经领取过
      const { data: existing } = await supabase
        .from('user_coupons')
        .select('id')
        .eq('user_id', user.id)
        .eq('coupon_id', coupon.id)
        .single();

      if (existing) {
        toast.error("您已经领取过这张优惠券了");
        return;
      }

      // 领取优惠券
      const { error } = await supabase
        .from('user_coupons')
        .insert({
          user_id: user.id,
          coupon_id: coupon.id,
          status: 'unused'
        });

      if (error) throw error;

      toast.success("优惠券领取成功！", {
        description: "已添加到您的优惠券列表"
      });

      onReceive?.(coupon.id);
    } catch (error) {
      console.error('领取优惠券失败:', error);
      toast.error("领取失败，请稍后重试");
    }
  };

  const formatDiscount = () => {
    if (coupon.type === 'percentage') {
      return `${coupon.discount_value}折`;
    }
    return `¥${coupon.discount_value}`;
  };

  const formatEndDate = () => {
    const date = new Date(coupon.end_date);
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric' 
    });
  };

  return (
    <Card className="bg-gradient-to-br from-orange-50 to-red-50 dark:from-orange-950/20 dark:to-red-950/20 border-orange-200 dark:border-orange-800 overflow-hidden hover:shadow-lg transition-all duration-300">
      <CardContent className="p-4">
        <div className="flex items-start gap-3">
          {/* 左侧折扣显示 */}
          <div className="flex-shrink-0 bg-gradient-to-br from-orange-500 to-red-500 text-white rounded-lg p-3 text-center min-w-[80px]">
            <Gift className="h-5 w-5 mx-auto mb-1" />
            <div className="text-2xl font-bold">{formatDiscount()}</div>
            <div className="text-xs opacity-90">优惠券</div>
          </div>

          {/* 右侧信息 */}
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2 mb-2">
              <h4 className="font-semibold text-foreground text-sm line-clamp-1">
                {coupon.name}
              </h4>
              <Badge variant="secondary" className="flex-shrink-0">
                <Tag className="h-3 w-3 mr-1" />
                {coupon.scope === 'all' ? '全场' : coupon.scope === 'category' ? '分类' : '商品'}
              </Badge>
            </div>

            {coupon.description && (
              <p className="text-xs text-muted-foreground mb-2 line-clamp-2">
                {coupon.description}
              </p>
            )}

            <div className="space-y-1 mb-3">
              {coupon.min_purchase_amount && coupon.min_purchase_amount > 0 && (
                <div className="text-xs text-muted-foreground">
                  满 ¥{coupon.min_purchase_amount} 可用
                </div>
              )}
              {coupon.max_discount_amount && coupon.max_discount_amount > 0 && (
                <div className="text-xs text-muted-foreground">
                  最高优惠 ¥{coupon.max_discount_amount}
                </div>
              )}
              <div className="flex items-center gap-1 text-xs text-orange-600 dark:text-orange-400">
                <Clock className="h-3 w-3" />
                <span>有效期至 {formatEndDate()}</span>
              </div>
            </div>

            <div className="flex items-center gap-2">
              <Button
                size="sm"
                className="flex-1 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white"
                onClick={handleReceive}
              >
                立即领取
              </Button>
              <div className="text-xs text-muted-foreground whitespace-nowrap">
                {coupon.code}
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
