import React, { useState } 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { PlusCircle, Edit, Trash2, Eye, PackageOpen, Star, TrendingUp } from 'lucide-react';
import ConfirmModal from '@/Components/ConfirmModal';
import { toast } from 'sonner';
import { useTranslation } from '@/hooks/useTranslation';
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger,
} from "@/Components/ui/hover-card";

export default function ProductIndex({ products }) {
    const { activeCurrency, currencies } = usePage().props;
    const { t } = useTranslation();

    const [isDeleteOpen, setIsDeleteOpen] = useState(false);
    const [productToDelete, setProductToDelete] = useState(null);

    const confirmDelete = (product) => {
        setProductToDelete(product);
        setIsDeleteOpen(true);
    };

    const handleDelete = () => {
        if (!productToDelete) return;
        router.delete(route('seller.products.destroy', productToDelete.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t('Product deleted successfully.'));
                setIsDeleteOpen(false);
            }
        });
    };

    const toggleFeature = (product) => {
        router.post(route('seller.products.toggle-featured', product.id), {}, {
            preserveScroll: true,
            onSuccess: (page) => toast.success(page.props.flash?.success || t('Featured status updated!'))
        });
    };

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

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title={t('Delete Product?')}
                description={t('Are you sure you want to delete ":title"? This cannot be undone.', { title: productToDelete?.title })}
                confirmText={t('Delete Product')}
                variant="destructive"
            />

            <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('Manage Products')}</h1>
                    <p className="text-muted-foreground">{t('View, edit, and manage your inventory.')}</p>
                </div>
                <Button className="bg-blue-600 hover:bg-blue-700 text-white gap-2" asChild>
                    <Link href={route('seller.products.create')}>
                        <PlusCircle className="w-4 h-4" /> {t('Add New Product')}
                    </Link>
                </Button>
            </div>

            <Card className="border-border/50 shadow-sm">
                <CardHeader>
                    <CardTitle>{t('All Products')}</CardTitle>
                    <CardDescription>{t('A complete list of your published catalog.')}</CardDescription>
                </CardHeader>
                <CardContent>
                    <div className="rounded-md border overflow-x-auto">
                        <Table>
                            <TableHeader className="bg-muted/50">
                                <TableRow>
                                    <TableHead className="w-[100px]">{t('Preview')}</TableHead>
                                    <TableHead className="min-w-[200px]">{t('Product Title')}</TableHead>
                                    <TableHead>{t('Category')}</TableHead>
                                    <TableHead>{t('Price')}</TableHead>
                                    <TableHead>{t('Stock')}</TableHead>
                                    <TableHead>{t('Sold')}</TableHead>
                                    <TableHead className="text-right">{t('Actions')}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {products.data.map((product) => {
                                    const mainImage = product.images?.find(img => img.is_main) || product.images?.[0];
                                    const imageSrc = mainImage ? `/storage/${mainImage.path}` : null;
                                    
                                    const productRate = currencies?.find(c => c.code === (product.currency_code || 'USD'))?.exchange_rate || 1;
                                    const baseUsdPrice = parseFloat(product.original_price || product.price || 0) / parseFloat(productRate);
                                    
                                    const targetRate = activeCurrency ? parseFloat(activeCurrency.exchange_rate) : 1;
                                    const displayPrice = (baseUsdPrice * targetRate).toFixed(2);
                                    const currencySymbol = activeCurrency?.symbol || '$';
                                    
                                    return (
                                        <TableRow key={product.id} className="group">
                                            <TableCell>
                                                <HoverCard openDelay={100} closeDelay={100}>
                                                    <HoverCardTrigger asChild>
                                                        <div className="w-14 h-14 rounded-lg border bg-muted flex items-center justify-center overflow-hidden cursor-zoom-in transition-all group-hover:border-primary/50">
                                                            {imageSrc ? (
                                                                <img src={imageSrc} alt={product.title} className="w-full h-full object-cover" />
                                                            ) : (
                                                                <PackageOpen className="w-6 h-6 text-muted-foreground opacity-30" />
                                                            )}
                                                        </div>
                                                    </HoverCardTrigger>
                                                    <HoverCardContent className="w-80 p-0 overflow-hidden shadow-2xl border-primary/20">
                                                        {imageSrc ? (
                                                            <div className="space-y-2">
                                                                <img src={imageSrc} alt={t('Large Preview')} className="w-full h-auto object-contain bg-white" />
                                                                <div className="p-3 bg-muted/30">
                                                                    <p className="text-xs font-bold truncate">{product.title}</p>
                                                                    <p className="text-[10px] text-muted-foreground">
                                                                        {t('Total Images: :count', { count: product.images?.length || 0 })}
                                                                    </p>
                                                                </div>
                                                            </div>
                                                        ) : (
                                                            <div className="p-4 text-center text-xs text-muted-foreground">{t('No image available')}</div>
                                                        )}
                                                    </HoverCardContent>
                                                </HoverCard>
                                            </TableCell>

                                            <TableCell className="font-medium">
                                                <div className="line-clamp-2 leading-snug" title={product.title}>
                                                    {product.title}
                                                </div>
                                                <div className="text-[10px] text-muted-foreground mt-1 font-mono uppercase flex items-center gap-2">
                                                    {t('ID:')} {product.id}
                                                    {product.is_featured && <Badge className="bg-amber-500 hover:bg-amber-600 text-white border-none py-0 px-1.5 h-4">{t('Featured')}</Badge>}
                                                </div>
                                            </TableCell>

                                            <TableCell className="text-muted-foreground text-sm">
                                                {product.category?.name || t('Uncategorized')}
                                            </TableCell>

                                            <TableCell>
                                                <div className="font-bold text-primary text-base">
                                                    {currencySymbol}{displayPrice}
                                                </div>
                                                {product.original_price && product.currency_code !== activeCurrency?.code && (
                                                    <div className="text-[10px] text-muted-foreground mt-0.5">
                                                        {t('Set at:')} {parseFloat(product.original_price).toFixed(2)} {product.currency_code}
                                                    </div>
                                                )}
                                            </TableCell>

                                            <TableCell>
                                                <div className="flex flex-col items-start">
                                                    <span className="text-sm font-semibold">{product.stock}</span>
                                                    <Badge variant="secondary" className={`text-[10px] h-4 px-1 mt-1 ${product.stock > 0 ? 'bg-green-500/10 text-green-600' : 'bg-red-500/10 text-red-600'}`}>
                                                        {product.stock > 0 ? t('In Stock') : t('Out of Stock')}
                                                    </Badge>
                                                </div>
                                            </TableCell>

                                            {/* --- NEW: TOTAL SOLD COLUMN --- */}
                                            <TableCell>
                                                <div className="flex flex-col items-start">
                                                    <span className="text-sm font-black text-foreground flex items-center gap-1">
                                                        {product.total_sold || 0}
                                                    </span>
                                                    <span className="text-[10px] text-muted-foreground font-bold uppercase tracking-wider mt-1 flex items-center gap-1">
                                                        <TrendingUp className="w-3 h-3 text-blue-500" /> {t('Units')}
                                                    </span>
                                                </div>
                                            </TableCell>

                                            <TableCell className="text-right">
                                                <div className="flex items-center justify-end gap-2">
                                                    <Button 
                                                        variant="outline" 
                                                        size="icon" 
                                                        onClick={() => toggleFeature(product)} 
                                                        title={product.is_featured ? t('Unfeature Product') : t('Feature Product')} 
                                                        className={`h-8 w-8 rounded-full transition-colors ${product.is_featured ? 'border-amber-300 bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/30' : 'hover:border-amber-200 hover:bg-amber-50'}`}
                                                    >
                                                        <Star className={`w-4 h-4 ${product.is_featured ? 'fill-amber-500 text-amber-500' : 'text-muted-foreground hover:text-amber-500'}`} />
                                                    </Button>

                                                    <Button variant="outline" size="icon" asChild title={t('View on Store')} className="h-8 w-8 rounded-full">
                                                        <a href={route('product.view', `${product.slug}_${product.id}`)} target="_blank" rel="noreferrer">
                                                            <Eye className="w-4 h-4 text-muted-foreground" />
                                                        </a>
                                                    </Button>

                                                    <Button variant="outline" size="icon" asChild title={t('Edit Product')} className="h-8 w-8 rounded-full hover:border-blue-200 hover:bg-blue-50">
                                                        <Link href={route('seller.products.edit', product.id)}>
                                                            <Edit className="w-4 h-4 text-blue-500" />
                                                        </Link>
                                                    </Button>

                                                    <Button 
                                                        variant="outline" 
                                                        size="icon" 
                                                        onClick={() => confirmDelete(product)} 
                                                        title={t('Delete Product')} 
                                                        className="h-8 w-8 rounded-full hover:border-red-200 hover:bg-red-50"
                                                    >
                                                        <Trash2 className="w-4 h-4 text-destructive" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    );
                                })}
                                
                                {products.data.length === 0 && (
                                    <TableRow>
                                        <TableCell colSpan="7" className="h-40 text-center text-muted-foreground">
                                            <div className="flex flex-col items-center justify-center opacity-30">
                                                <PackageOpen className="w-12 h-12 mb-2" />
                                                <p className="text-sm font-medium">{t('No products found')}</p>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </div>

                    {products.links && products.links.length > 3 && (
                        <div className="flex justify-between items-center mt-6">
                            <span className="text-xs text-muted-foreground font-medium">
                                {t('Showing page :current of :last (:total products)', {
                                    current: products.current_page,
                                    last: products.last_page,
                                    total: products.total
                                })}
                            </span>
                            <div className="flex gap-1">
                                {products.links.map((link, i) => (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`px-3 py-1 border rounded-md text-xs transition-all ${link.active ? 'bg-primary text-primary-foreground border-primary shadow-sm' : 'bg-background hover:bg-muted'} ${!link.url && 'opacity-30 cursor-not-allowed'}`}
                                        dangerouslySetInnerHTML={{ __html: link.label }}
                                    />
                                ))}
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
        </DashboardLayout>
    );
}