import React from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/Components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Badge } from "@/Components/ui/badge";
import { Button } from "@/Components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Store, Package, DollarSign, PlusCircle, ShoppingCart, Activity } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

export default function SellerDashboard({ stats, chartData, availableYears, filters, recentSales }) {
    const { t } = useTranslation();
    const { activeCurrency } = usePage().props;

    // Convert the base currency amounts to the seller's active viewing currency
    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
    const currencySymbol = activeCurrency?.symbol || '$';
    
    const sales30DaysConverted = (stats.sales_30d_base * targetRate).toFixed(2);

    // Prevent division by zero for the chart
    const maxChartValue = Math.max(...chartData.map(d => d.amount * targetRate), 1);

    const getStatusBadge = (status) => {
        const styles = {
            pending: 'bg-zinc-500/10 text-zinc-600',
            processing: 'bg-orange-500/10 text-orange-600',
            shipped: 'bg-blue-500/10 text-blue-600',
            completed: 'bg-green-500/10 text-green-600',
            cancelled: 'bg-red-500/10 text-red-600',
            refunded: 'bg-purple-500/10 text-purple-600',
        };

        const labels = { 
            pending: t('Awaiting Payment'), 
            processing: t('Needs Shipping'), 
            shipped: t('Shipped'), 
            completed: t('Completed'), 
            cancelled: t('Cancelled'), 
            refunded: t('Refunded') 
        };

        return (
            <Badge variant="secondary" className={`${styles[status] || 'bg-muted'} uppercase text-[10px] tracking-wider font-bold`}>
                {labels[status] || status}
            </Badge>
        );
    };

    const handleYearChange = (val) => {
        router.get(route('dashboard.seller'), { year: val }, { 
            preserveState: true, 
            preserveScroll: true 
        });
    };

    return (
        <DashboardLayout mode="seller">
            <Head title={t('Seller Center')} />

            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{t('Seller Center')}</h1>
                    <p className="text-muted-foreground">{t('Manage your shop, products, and sales performance.')}</p>
                </div>
                
                <Button className="bg-blue-600 hover:bg-blue-700 text-white gap-2 shadow-sm" asChild>
                    <Link href={route('seller.products.create')}>
                        <PlusCircle className="w-4 h-4" /> {t('Add New Product')}
                    </Link>
                </Button>
            </div>

            {/* --- TOP 4 METRICS --- */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <Card className="border-border/50 shadow-sm">
                    <CardContent className="p-6 flex flex-col gap-2">
                        <DollarSign className="w-6 h-6 text-green-500 mb-2" />
                        <div className="text-2xl font-black">{currencySymbol}{sales30DaysConverted}</div>
                        <p className="text-sm text-muted-foreground">{t('Sales Volume (30 Days)')}</p>
                    </CardContent>
                </Card>
                <Card className="border-border/50 shadow-sm">
                    <CardContent className="p-6 flex flex-col gap-2">
                        <ShoppingCart className="w-6 h-6 text-blue-500 mb-2" />
                        <div className="text-2xl font-black">{stats.total_sales.toLocaleString()}</div>
                        <p className="text-sm text-muted-foreground">{t('Total Orders Sold')}</p>
                    </CardContent>
                </Card>
                <Card className="border-border/50 shadow-sm">
                    <CardContent className="p-6 flex flex-col gap-2">
                        <Package className="w-6 h-6 text-purple-500 mb-2" />
                        <div className="text-2xl font-bold">{stats.active_products.toLocaleString()}</div>
                        <p className="text-sm text-muted-foreground">{t('Active Products')}</p>
                    </CardContent>
                </Card>
                <Card className="border-orange-500/50 bg-orange-500/5 shadow-sm">
                    <CardContent className="p-6 flex flex-col gap-2">
                        <Store className="w-6 h-6 text-orange-500 mb-2" />
                        <div className="text-2xl font-bold text-orange-600">{stats.pending_orders.toLocaleString()}</div>
                        <p className="text-sm text-orange-600/80">{t('Pending Orders')}</p>
                    </CardContent>
                </Card>
            </div>

            {/* --- CHART & RECENT SALES GRID --- */}
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 mb-8">
                
                {/* CHART SECTION */}
                <Card className="xl:col-span-2 border-border/50 shadow-sm flex flex-col">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 border-b">
                        <div>
                            <CardTitle className="flex items-center gap-2">
                                <Activity className="w-5 h-5 text-primary" /> {t('Sales Volume History')}
                            </CardTitle>
                            <CardDescription>{t('Monthly total sold value converted to your active currency.')}</CardDescription>
                        </div>
                        <Select value={filters.year?.toString()} onValueChange={handleYearChange}>
                            <SelectTrigger className="w-[100px] sm:w-[120px] bg-background shadow-sm">
                                <SelectValue placeholder={t('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-6">
                        <div className="flex h-64 items-end gap-2 sm:gap-4 w-full mt-auto border-b border-border/50 pb-2">
                            {chartData.map((data, idx) => {
                                const convertedAmount = data.amount * targetRate;
                                const heightPercentage = (convertedAmount / maxChartValue) * 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-md"
                                            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-bold uppercase tracking-wider">
                                            {t(data.month)}
                                        </span>
                                    </div>
                                );
                            })}
                        </div>
                    </CardContent>
                </Card>

                {/* RECENT SALES SECTION */}
                <Card className="xl:col-span-1 border-border/50 shadow-sm flex flex-col">
                    <CardHeader className="border-b pb-4 flex flex-row items-center justify-between">
                        <div>
                            <CardTitle>{t('Recent Sales')}</CardTitle>
                            <CardDescription>{t('Needs your attention')}</CardDescription>
                        </div>
                    </CardHeader>
                    <CardContent className="p-0 flex-1 overflow-x-auto">
                        <Table>
                            <TableHeader className="bg-muted/30">
                                <TableRow>
                                    <TableHead>{t('Order')}</TableHead>
                                    <TableHead className="text-right">{t('Action')}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {recentSales.map((sale) => (
                                    <TableRow key={sale.id}>
                                        <TableCell className="py-3">
                                            <div className="font-bold text-sm truncate max-w-[150px] sm:max-w-[200px]" title={sale.product_names}>
                                                {sale.product_names || t('Product Removed')}
                                            </div>
                                            <div className="text-xs text-muted-foreground mt-1 flex items-center justify-between">
                                                <span className="font-mono text-primary">{sale.order_number}</span>
                                                <span className="font-black text-green-600">{sale.total}</span>
                                            </div>
                                            <div className="mt-1">{getStatusBadge(sale.status)}</div>
                                        </TableCell>
                                        <TableCell className="text-right py-3 align-top">
                                            <Button variant="secondary" size="sm" className="bg-blue-50 text-blue-600 hover:bg-blue-100 border border-blue-200 shadow-sm" asChild>
                                                <Link href={route('seller.orders.index', { search: sale.order_number })}>
                                                    {sale.status === 'processing' ? t('Fulfill') : t('Details')}
                                                </Link>
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                                {recentSales.length === 0 && (
                                    <TableRow>
                                        <TableCell colSpan="2" className="text-center py-10 text-muted-foreground">
                                            {t('No recent sales found.')}
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            </div>
        </DashboardLayout>
    );
}