import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Loader2, TrendingUp, Users, CreditCard, Package, ExternalLink, ArrowUpRight } from "lucide-react";

interface Stats {
    total: number;
    active: number;
    pending: number;
    on_hold: number;
    cancelled: number;
    expired: number;
    monthly_revenue: number;
    new_this_month: number;
    subscription_products?: number;
}

export function OverviewTab() {
    const [stats, setStats] = useState<Stats | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchStats();
    }, []);

    const fetchStats = async () => {
        setLoading(true);
        try {
            const apiUrl = window.swiftCommerceData?.apiUrl || '/wp-json/swift-commerce/v1';
            const response = await fetch(
                `${apiUrl}/subscriptions/stats`,
                {
                    headers: {
                        'X-WP-Nonce': window.swiftCommerceData?.restNonce || '',
                    },
                }
            );
            const data = await response.json();
            if (data.success) {
                setStats(data.stats);
            }
        } catch (error) {
            console.error('Failed to fetch stats:', error);
            // Set default stats if API fails
            setStats({
                total: 0,
                active: 0,
                pending: 0,
                on_hold: 0,
                cancelled: 0,
                expired: 0,
                monthly_revenue: 0,
                new_this_month: 0,
            });
        } finally {
            setLoading(false);
        }
    };

    const createSubscriptionProduct = () => {
        window.open('/wp-admin/post-new.php?post_type=product', '_blank');
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Quick Stats */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Total Subscriptions</CardTitle>
                        <CreditCard className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{stats?.total || 0}</div>
                        <p className="text-xs text-muted-foreground">
                            All time subscriptions created
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Active Subscriptions</CardTitle>
                        <Users className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold text-green-600">{stats?.active || 0}</div>
                        <p className="text-xs text-muted-foreground">
                            Currently active subscribers
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">New This Month</CardTitle>
                        <TrendingUp className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{stats?.new_this_month || 0}</div>
                        <p className="text-xs text-muted-foreground">
                            Subscriptions started this month
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Subscription Products</CardTitle>
                        <Package className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold text-blue-600">{stats?.subscription_products || 0}</div>
                        <p className="text-xs text-muted-foreground">
                            Products with subscription pricing
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Quick Actions */}
            <Card>
                <CardHeader>
                    <CardTitle>Quick Actions</CardTitle>
                    <CardDescription>
                        Common subscription management tasks
                    </CardDescription>
                </CardHeader>
                <CardContent className="grid gap-4 sm:grid-cols-3">
                    <Button 
                        className="justify-start" 
                        variant="outline"
                        onClick={createSubscriptionProduct}
                    >
                        <Package className="h-4 w-4 mr-2" />
                        Create Subscription Product
                        <ExternalLink className="h-4 w-4 ml-auto" />
                    </Button>
                    <Button 
                        className="justify-start" 
                        variant="outline"
                        onClick={() => window.open('/wp-admin/edit.php?post_type=product&product_type=subscription', '_blank')}
                    >
                        <CreditCard className="h-4 w-4 mr-2" />
                        View Subscription Products
                        <ExternalLink className="h-4 w-4 ml-auto" />
                    </Button>
                    <Button 
                        className="justify-start" 
                        variant="outline"
                        onClick={() => window.open('/wp-admin/admin.php?page=wc-settings&tab=email', '_blank')}
                    >
                        <ArrowUpRight className="h-4 w-4 mr-2" />
                        Configure Emails
                        <ExternalLink className="h-4 w-4 ml-auto" />
                    </Button>
                </CardContent>
            </Card>
        </div>
    );
}
