import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuth } from "@/contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { ArrowLeft, Ticket, Clock, CheckCircle, XCircle } from "lucide-react";
import { format } from "date-fns";
import { useToast } from "@/hooks/use-toast";

interface UserCoupon {
  id: string;
  coupon_id: string;
  status: string;
  received_at: string;
  used_at: string | null;
  coupon: {
    code: string;
    name: string;
    description: string;
    type: string;
    discount_value: number;
    min_purchase_amount: number | null;
    max_discount_amount: number | null;
    start_date: string;
    end_date: string;
  };
}

export default function CouponsPage() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [coupons, setCoupons] = useState<UserCoupon[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("unused");

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

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

    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('user_coupons')
        .select(`
          id,
          coupon_id,
          status,
          received_at,
          used_at,
          coupons (
            code,
            name,
            description,
            type,
            discount_value,
            min_purchase_amount,
            max_discount_amount,
            start_date,
            end_date
          )
        `)
        .eq('user_id', user.id)
        .order('received_at', { ascending: false });

      if (error) throw error;

      const formattedCoupons = (data || []).map((item: any) => ({
        id: item.id,
        coupon_id: item.coupon_id,
        status: item.status,
        received_at: item.received_at,
        used_at: item.used_at,
        coupon: item.coupons
      }));

      setCoupons(formattedCoupons);
    } catch (error: any) {
      console.error('获取优惠券失败:', error);
      toast({
        title: "获取优惠券失败",
        description: error.message,
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const formatDiscount = (type: string, value: number) => {
    if (type === 'percentage') {
      return `${value}折`;
    }
    return `¥${value}`;
  };

  const isExpired = (endDate: string) => {
    return new Date(endDate) < new Date();
  };

  const getStatusBadge = (status: string, endDate: string) => {
    if (isExpired(endDate)) {
      return <Badge variant="secondary" className="bg-muted text-muted-foreground">已过期</Badge>;
    }
    
    switch (status) {
      case 'unused':
        return <Badge variant="default" className="bg-success text-success-foreground">未使用</Badge>;
      case 'used':
        return <Badge variant="secondary">已使用</Badge>;
      case 'expired':
        return <Badge variant="secondary" className="bg-muted text-muted-foreground">已过期</Badge>;
      default:
        return <Badge variant="secondary">{status}</Badge>;
    }
  };

  const filterCoupons = (status: string) => {
    return coupons.filter(c => {
      if (status === 'unused') {
        return c.status === 'unused' && !isExpired(c.coupon.end_date);
      }
      if (status === 'used') {
        return c.status === 'used';
      }
      if (status === 'expired') {
        return c.status === 'expired' || (c.status === 'unused' && isExpired(c.coupon.end_date));
      }
      return true;
    });
  };

  const CouponCard = ({ userCoupon }: { userCoupon: UserCoupon }) => {
    const { coupon } = userCoupon;
    const expired = isExpired(coupon.end_date);

    return (
      <Card className={`border-border transition-all hover:shadow-md ${expired ? 'opacity-60' : ''}`}>
        <CardContent className="p-6">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* 左侧优惠信息 */}
            <div className="flex items-center justify-center sm:justify-start p-4 bg-gradient-to-br from-primary/10 to-primary/5 rounded-lg min-w-[120px]">
              <div className="text-center">
                <div className="text-3xl font-bold text-primary mb-1">
                  {formatDiscount(coupon.type, coupon.discount_value)}
                </div>
                <div className="text-xs text-muted-foreground">
                  {coupon.type === 'percentage' ? '折扣' : '立减'}
                </div>
              </div>
            </div>

            {/* 右侧详细信息 */}
            <div className="flex-1 space-y-2">
              <div className="flex items-start justify-between gap-2">
                <div>
                  <h3 className="font-semibold text-lg text-foreground">{coupon.name}</h3>
                  {coupon.description && (
                    <p className="text-sm text-muted-foreground mt-1">{coupon.description}</p>
                  )}
                </div>
                {getStatusBadge(userCoupon.status, coupon.end_date)}
              </div>

              <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                {coupon.min_purchase_amount && (
                  <div>满 ¥{coupon.min_purchase_amount} 可用</div>
                )}
                {coupon.max_discount_amount && coupon.type === 'percentage' && (
                  <div>最高优惠 ¥{coupon.max_discount_amount}</div>
                )}
              </div>

              <div className="flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-muted-foreground pt-2 border-t border-border">
                <div className="flex items-center gap-1">
                  <Ticket className="h-3 w-3" />
                  <span>优惠码: {coupon.code}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Clock className="h-3 w-3" />
                  <span>有效期至: {format(new Date(coupon.end_date), 'yyyy-MM-dd')}</span>
                </div>
              </div>

              {userCoupon.used_at && (
                <div className="text-xs text-muted-foreground flex items-center gap-1">
                  <CheckCircle className="h-3 w-3" />
                  <span>使用时间: {format(new Date(userCoupon.used_at), 'yyyy-MM-dd HH:mm')}</span>
                </div>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-foreground mb-2">请先登录</h2>
          <p className="text-muted-foreground">您需要登录才能查看优惠券</p>
        </div>
      </div>
    );
  }

  const unusedCoupons = filterCoupons('unused');
  const usedCoupons = filterCoupons('used');
  const expiredCoupons = filterCoupons('expired');

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted">
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-8">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-4">
              <Button 
                onClick={() => navigate(-1)} 
                variant="outline" 
                size="sm"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                返回
              </Button>
              <div>
                <h1 className="text-3xl font-bold text-foreground">我的优惠券</h1>
                <p className="text-muted-foreground mt-1">查看和管理您的优惠券</p>
              </div>
            </div>
          </div>

          {/* 统计卡片 */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-6">
            <Card className="border-border">
              <CardContent className="p-4 flex items-center gap-3">
                <div className="p-3 bg-success/10 rounded-lg">
                  <Ticket className="h-6 w-6 text-success" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{unusedCoupons.length}</div>
                  <div className="text-sm text-muted-foreground">可用优惠券</div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-border">
              <CardContent className="p-4 flex items-center gap-3">
                <div className="p-3 bg-primary/10 rounded-lg">
                  <CheckCircle className="h-6 w-6 text-primary" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{usedCoupons.length}</div>
                  <div className="text-sm text-muted-foreground">已使用</div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-border">
              <CardContent className="p-4 flex items-center gap-3">
                <div className="p-3 bg-muted rounded-lg">
                  <XCircle className="h-6 w-6 text-muted-foreground" />
                </div>
                <div>
                  <div className="text-2xl font-bold text-foreground">{expiredCoupons.length}</div>
                  <div className="text-sm text-muted-foreground">已过期</div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 优惠券列表 */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-3 mb-6">
            <TabsTrigger value="unused">
              未使用 ({unusedCoupons.length})
            </TabsTrigger>
            <TabsTrigger value="used">
              已使用 ({usedCoupons.length})
            </TabsTrigger>
            <TabsTrigger value="expired">
              已过期 ({expiredCoupons.length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="unused" className="space-y-4">
            {loading ? (
              <Card className="border-border">
                <CardContent className="p-8 text-center text-muted-foreground">
                  加载中...
                </CardContent>
              </Card>
            ) : unusedCoupons.length === 0 ? (
              <Card className="border-border">
                <CardContent className="p-8 text-center text-muted-foreground">
                  暂无可用优惠券
                </CardContent>
              </Card>
            ) : (
              unusedCoupons.map(coupon => (
                <CouponCard key={coupon.id} userCoupon={coupon} />
              ))
            )}
          </TabsContent>

          <TabsContent value="used" className="space-y-4">
            {usedCoupons.length === 0 ? (
              <Card className="border-border">
                <CardContent className="p-8 text-center text-muted-foreground">
                  暂无已使用优惠券
                </CardContent>
              </Card>
            ) : (
              usedCoupons.map(coupon => (
                <CouponCard key={coupon.id} userCoupon={coupon} />
              ))
            )}
          </TabsContent>

          <TabsContent value="expired" className="space-y-4">
            {expiredCoupons.length === 0 ? (
              <Card className="border-border">
                <CardContent className="p-8 text-center text-muted-foreground">
                  暂无已过期优惠券
                </CardContent>
              </Card>
            ) : (
              expiredCoupons.map(coupon => (
                <CouponCard key={coupon.id} userCoupon={coupon} />
              ))
            )}
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
