import React from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/Components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/Components/ui/tooltip";
import { 
    DollarSign, ShoppingCart, Users, Package, 
    ArrowRight, MapPin, Mail, CreditCard, ShieldCheck, 
    Store, AlertCircle, Tags, Globe, Server, Activity, 
    ArrowUpRight, ArrowDownRight, PackageOpen, TrendingUp, Clock, Info
} from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

export default function Dashboard({ stats, monthlySalesData, recentSales, topProducts, filters, availableYears }) {
    
    const { t } = useTranslation();
    const { activeCurrency } = usePage().props;
    
    // Convert the base currency amounts to the admin's active viewing currency
    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
    const currencySymbol = activeCurrency?.symbol || '$';

    const totalSoldConverted = (stats.total_sold_volume * targetRate).toFixed(2);

    // Prevent division by zero if there's no data yet
    const maxSalesValue = Math.max(...monthlySalesData.map(d => d.amount * targetRate), 1);

    // Handle Year Change for the Graph
    const handleYearChange = (val) => {
        router.get(route('cp.dashboard'), { year: val }, { 
            preserveState: true, 
            preserveScroll: true 
        });
    };

    return (
        <AdminLayout>
            <Head title="Admin Dashboard" />
            
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                <div>
                    <h2 className="text-2xl font-bold tracking-tight">System Overview</h2>
                    <p className="text-muted-foreground text-sm">Welcome to the central control panel. Here is what's happening today.</p>
                </div>
                
                <div className="flex items-center gap-2 bg-muted/30 border border-border/50 px-3 py-1.5 rounded-lg w-fit">
                    <span className="text-xs font-bold text-muted-foreground uppercase tracking-widest">Viewing in:</span>
                    <span className="text-sm font-black text-primary">{activeCurrency?.code || 'USD'} ({currencySymbol})</span>
                    <TooltipProvider>
                        <Tooltip delayDuration={100}>
                            <TooltipTrigger type="button" className="cursor-help">
                                <Info className="w-4 h-4 text-muted-foreground hover:text-foreground transition-colors" />
                            </TooltipTrigger>
                            <TooltipContent className="max-w-xs">
                                <p className="text-xs">
                                    All global sales values are automatically converted from their native transaction currencies into your currently selected currency ({activeCurrency?.code || 'USD'}) based on live exchange rates.
                                </p>
                            </TooltipContent>
                        </Tooltip>
                    </TooltipProvider>
                </div>
            </div>

            {/* --- TOP 4 METRIC CARDS --- */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
                <Card className="border-border/50 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Total Sold Value</CardTitle>
                        <div className="p-2 bg-green-500/10 rounded-lg"><DollarSign className="w-4 h-4 text-green-600" /></div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-black">{currencySymbol}{totalSoldConverted}</div>
                        <p className={`text-xs flex items-center mt-1 font-bold ${stats.sold_growth >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                            {stats.sold_growth >= 0 ? <ArrowUpRight className="w-3 h-3 mr-1" /> : <ArrowDownRight className="w-3 h-3 mr-1" />}
                            {stats.sold_growth > 0 ? '+' : ''}{stats.sold_growth}% from last month
                        </p>
                    </CardContent>
                </Card>

                <Card className="border-border/50 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Total Sales (Orders)</CardTitle>
                        <div className="p-2 bg-blue-500/10 rounded-lg"><ShoppingCart className="w-4 h-4 text-blue-600" /></div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-black">{stats.total_orders.toLocaleString()}</div>
                        <p className={`text-xs flex items-center mt-1 font-bold ${stats.sales_growth >= 0 ? 'text-blue-500' : 'text-red-500'}`}>
                            {stats.sales_growth >= 0 ? <ArrowUpRight className="w-3 h-3 mr-1" /> : <ArrowDownRight className="w-3 h-3 mr-1" />}
                            {stats.sales_growth > 0 ? '+' : ''}{stats.sales_growth}% from last month
                        </p>
                    </CardContent>
                </Card>

                <Card className="border-border/50 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Total Users</CardTitle>
                        <div className="p-2 bg-purple-500/10 rounded-lg"><Users className="w-4 h-4 text-purple-600" /></div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-black">{stats.total_users.toLocaleString()}</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            Including {stats.total_stores} active stores/sellers
                        </p>
                    </CardContent>
                </Card>

                <Card className="border-border/50 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium text-muted-foreground">Active Products</CardTitle>
                        <div className="p-2 bg-orange-500/10 rounded-lg"><Package className="w-4 h-4 text-orange-600" /></div>
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-black">{stats.total_products.toLocaleString()}</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            Published across the marketplace
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* --- MIDDLE ROW: GRAPH & SETUP GUIDE --- */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
                
                {/* 1. SALES GRAPH (Custom CSS Bar Chart) */}
                <Card className="lg:col-span-2 border-border/50 shadow-sm flex flex-col">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <div>
                            <CardTitle>Sales Volume Overview</CardTitle>
                            <CardDescription>Monthly transaction volume converted to your active currency.</CardDescription>
                        </div>
                        <Select value={filters.year?.toString()} onValueChange={handleYearChange}>
                            <SelectTrigger className="w-[120px] bg-background">
                                <SelectValue placeholder="Select Year" />
                            </SelectTrigger>
                            <SelectContent>
                                {availableYears.map(year => (
                                    <SelectItem key={year} value={year.toString()}>{year}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </CardHeader>
                    <CardContent className="flex-1 flex flex-col justify-end pt-4">
                        <div className="flex h-64 items-end gap-2 sm:gap-4 w-full mt-auto border-b border-border/50 pb-2">
                            {monthlySalesData.map((data, idx) => {
                                const convertedAmount = data.amount * targetRate;
                                const heightPercentage = (convertedAmount / maxSalesValue) * 100;
                                return (
                                    <div key={idx} className="flex-1 flex flex-col items-center justify-end group h-full relative">
                                        {/* Tooltip on hover */}
                                        <div className="opacity-0 group-hover:opacity-100 transition-opacity text-xs font-bold bg-foreground text-background px-2 py-1 rounded mb-2 absolute top-0 -translate-y-full whitespace-nowrap pointer-events-none z-10">
                                            {currencySymbol}{convertedAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                                        </div>
                                        {/* Bar */}
                                        <div 
                                            className="w-full bg-primary/20 group-hover:bg-primary transition-colors rounded-t-sm"
                                            style={{ height: `${Math.max(heightPercentage, 1)}%` }} // Minimum 1% to show a tiny sliver if 0
                                        ></div>
                                        {/* Label */}
                                        <span className="text-[10px] sm:text-xs text-muted-foreground mt-2 font-medium uppercase tracking-wider">
                                            {data.month}
                                        </span>
                                    </div>
                                );
                            })}
                        </div>
                    </CardContent>
                </Card>

                {/* 2. SYSTEM SETUP GUIDE */}
                <Card className="border-primary/20 bg-primary/5 shadow-sm flex flex-col">
                    <CardHeader className="pb-3 border-b border-primary/10 bg-primary/10">
                        <CardTitle className="text-lg text-primary flex items-center gap-2">
                            <Activity className="w-5 h-5" /> Launch Checklist
                        </CardTitle>
                        <CardDescription>Essential steps to get your marketplace operational.</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0 flex-1 overflow-y-auto">
                        <div className="divide-y divide-primary/10">
                            
                            <Link href={route('cp.settings.globalization')} className="flex items-start gap-4 p-4 hover:bg-primary/10 transition-colors group">
                                <div className="p-2 bg-background border rounded-md group-hover:border-primary/50 text-blue-500 shrink-0">
                                    <MapPin className="w-4 h-4" />
                                </div>
                                <div className="flex-1">
                                    <h4 className="text-sm font-bold text-foreground">Location & IP Setup</h4>
                                    <p className="text-xs text-muted-foreground mt-0.5">Import IP2Location CSV data for countries and regions.</p>
                                </div>
                                <ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary mt-1 shrink-0" />
                            </Link>

                            <Link href={route('cp.settings.smtp')} className="flex items-start gap-4 p-4 hover:bg-primary/10 transition-colors group">
                                <div className="p-2 bg-background border rounded-md group-hover:border-primary/50 text-orange-500 shrink-0">
                                    <Mail className="w-4 h-4" />
                                </div>
                                <div className="flex-1">
                                    <h4 className="text-sm font-bold text-foreground">Configure SMTP Mailer</h4>
                                    <p className="text-xs text-muted-foreground mt-0.5">Enable system emails for passwords and orders.</p>
                                </div>
                                <ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary mt-1 shrink-0" />
                            </Link>

                            <Link href={route('cp.settings.payments')} className="flex items-start gap-4 p-4 hover:bg-primary/10 transition-colors group">
                                <div className="p-2 bg-background border rounded-md group-hover:border-primary/50 text-green-500 shrink-0">
                                    <CreditCard className="w-4 h-4" />
                                </div>
                                <div className="flex-1">
                                    <h4 className="text-sm font-bold text-foreground">Payment Gateways</h4>
                                    <p className="text-xs text-muted-foreground mt-0.5">Add Stripe, PayPal, or Local Gateways APIs.</p>
                                </div>
                                <ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary mt-1 shrink-0" />
                            </Link>

                            <Link href={route('cp.settings.trust')} className="flex items-start gap-4 p-4 hover:bg-primary/10 transition-colors group">
                                <div className="p-2 bg-background border rounded-md group-hover:border-primary/50 text-purple-500 shrink-0">
                                    <ShieldCheck className="w-4 h-4" />
                                </div>
                                <div className="flex-1">
                                    <h4 className="text-sm font-bold text-foreground">Trust & Refunds</h4>
                                    <p className="text-xs text-muted-foreground mt-0.5">Setup buyer protection badges and refund systems.</p>
                                </div>
                                <ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary mt-1 shrink-0" />
                            </Link>

                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* --- NEW ROW: RECENT SALES & TOP PRODUCTS --- */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
                {/* RECENT TRANSACTIONS */}
                <Card className="lg:col-span-2 border-border/50 shadow-sm flex flex-col">
                    <CardHeader className="border-b pb-4">
                        <CardTitle className="flex items-center gap-2">
                            <Clock className="w-5 h-5 text-primary" /> Recent Transactions
                        </CardTitle>
                        <CardDescription>Latest successfully paid or shipped items.</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="divide-y divide-border">
                            {recentSales.map(sale => (
                                <div key={sale.id} className="flex items-center gap-4 p-4 hover:bg-muted/30 transition-colors">
                                    <div className="w-12 h-12 rounded border bg-white overflow-hidden shrink-0 flex items-center justify-center">
                                        {sale.image_path ? (
                                            <img src={`/storage/${sale.image_path}`} alt="" className="w-full h-full object-contain" />
                                        ) : (
                                            <PackageOpen className="w-5 h-5 text-muted-foreground/30" />
                                        )}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        {sale.slug ? (
                                            <Link href={route('product.view', `${sale.slug}_${sale.product_id}`)} target="_blank" className="font-bold text-sm truncate block hover:text-primary transition-colors">
                                                {sale.title}
                                            </Link>
                                        ) : (
                                            <p className="font-bold text-sm truncate text-muted-foreground">{sale.title}</p>
                                        )}
                                        <p className="text-xs text-muted-foreground mt-0.5 flex items-center gap-1">
                                            <span className="font-medium text-foreground">{sale.buyer}</span> • {sale.time}
                                        </p>
                                    </div>
                                    <div className="text-right shrink-0">
                                        <p className="font-black text-sm text-green-600">+{sale.currency} {parseFloat(sale.price).toLocaleString()}</p>
                                        <p className="text-[10px] font-bold text-muted-foreground uppercase">Qty: {sale.qty}</p>
                                    </div>
                                </div>
                            ))}
                            {recentSales.length === 0 && (
                                <div className="p-8 text-center text-muted-foreground text-sm">
                                    No completed transactions found yet.
                                </div>
                            )}
                        </div>
                    </CardContent>
                </Card>

                {/* TOP PERFORMING PRODUCTS */}
                <Card className="border-border/50 shadow-sm flex flex-col">
                    <CardHeader className="border-b pb-4">
                        <CardTitle className="flex items-center gap-2">
                            <TrendingUp className="w-5 h-5 text-blue-500" /> Top Products
                        </CardTitle>
                        <CardDescription>Highest selling products of all time.</CardDescription>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="divide-y divide-border">
                            {topProducts.map(product => (
                                <div key={product.id} className="flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors">
                                    <div className="w-10 h-10 rounded border bg-white overflow-hidden shrink-0 flex items-center justify-center">
                                        {product.image_path ? (
                                            <img src={`/storage/${product.image_path}`} alt="" className="w-full h-full object-contain" />
                                        ) : (
                                            <PackageOpen className="w-4 h-4 text-muted-foreground/30" />
                                        )}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        {product.slug ? (
                                            <Link href={route('product.view', `${product.slug}_${product.id}`)} target="_blank" className="font-bold text-sm truncate block hover:text-primary transition-colors">
                                                {product.title}
                                            </Link>
                                        ) : (
                                            <p className="font-bold text-sm truncate text-muted-foreground">{product.title}</p>
                                        )}
                                        <p className="text-xs text-muted-foreground mt-0.5 truncate">
                                            <Store className="w-3 h-3 inline mr-1"/>{product.seller}
                                        </p>
                                    </div>
                                    <div className="text-right shrink-0 bg-blue-500/10 px-2 py-1 rounded-md border border-blue-500/20">
                                        <p className="font-black text-xs text-blue-700 dark:text-blue-400">{product.total_sold} Sold</p>
                                    </div>
                                </div>
                            ))}
                            {topProducts.length === 0 && (
                                <div className="p-8 text-center text-muted-foreground text-sm">
                                    No product sales recorded yet.
                                </div>
                            )}
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* --- BOTTOM ROW: 6 EXTRA INFO CARDS --- */}
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
                
                <Card className="border-border/50 shadow-sm hover:shadow-md transition-shadow">
                    <CardContent className="p-4">
                        <div className="flex items-center gap-3 mb-2">
                            <Store className="w-4 h-4 text-primary" />
                            <h3 className="text-xs font-bold text-muted-foreground uppercase">Total Stores</h3>
                        </div>
                        <div className="text-xl font-black">{stats.total_stores}</div>
                    </CardContent>
                </Card>

                <Link href={route('cp.transactions.index')} className="block">
                    <Card className="border-border/50 shadow-sm hover:shadow-md transition-all h-full">
                        <CardContent className="p-4">
                            <div className="flex items-center gap-3 mb-2">
                                <Activity className="w-4 h-4 text-blue-500" />
                                <h3 className="text-xs font-bold text-muted-foreground uppercase">Total Orders</h3>
                            </div>
                            <div className="text-xl font-black">{stats.total_orders}</div>
                        </CardContent>
                    </Card>
                </Link>

                <Link href={route('cp.users.index')} className="block">
                    <Card className="border-orange-500/30 shadow-sm bg-orange-500/5 hover:bg-orange-500/10 transition-colors h-full">
                        <CardContent className="p-4">
                            <div className="flex items-center gap-3 mb-2">
                                <AlertCircle className="w-4 h-4 text-orange-600" />
                                <h3 className="text-xs font-bold text-orange-700 dark:text-orange-500 uppercase">Refunds</h3>
                            </div>
                            <div className="text-xl font-black text-orange-700 dark:text-orange-500">{stats.refund_requests}</div>
                        </CardContent>
                    </Card>
                </Link>

                <Card className="border-border/50 shadow-sm hover:shadow-md transition-shadow">
                    <CardContent className="p-4">
                        <div className="flex items-center gap-3 mb-2">
                            <Tags className="w-4 h-4 text-muted-foreground" />
                            <h3 className="text-xs font-bold text-muted-foreground uppercase">Categories</h3>
                        </div>
                        <div className="text-xl font-black">{stats.total_categories}</div>
                    </CardContent>
                </Card>

                <Card className="border-border/50 shadow-sm hover:shadow-md transition-shadow">
                    <CardContent className="p-4">
                        <div className="flex items-center gap-3 mb-2">
                            <Globe className="w-4 h-4 text-muted-foreground" />
                            <h3 className="text-xs font-bold text-muted-foreground uppercase">Countries</h3>
                        </div>
                        <div className="text-xl font-black">{stats.active_countries}</div>
                    </CardContent>
                </Card>

                <Card className="border-green-500/30 shadow-sm bg-green-500/5">
                    <CardContent className="p-4 flex flex-col justify-center h-full">
                        <div className="flex items-center gap-3 mb-2">
                            <Server className="w-4 h-4 text-green-600" />
                            <h3 className="text-xs font-bold text-green-700 dark:text-green-500 uppercase">System Status</h3>
                        </div>
                        <div className="text-sm font-black text-green-700 dark:text-green-500 mt-1 flex items-center gap-1.5">
                            <span className="w-2.5 h-2.5 rounded-full bg-green-500 animate-pulse shadow-[0_0_8px_rgba(34,197,94,0.6)]"></span> Online
                        </div>
                    </CardContent>
                </Card>

            </div>

        </AdminLayout>
    );
}