import { Head, Link, router } from '@inertiajs/react';
import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import { 
    History, 
    Filter, 
    Search, 
    Calendar, 
    User, 
    Building, 
    Package, 
    Truck, 
    CreditCard, 
    Download, 
    FileSpreadsheet, 
    ChevronDown, 
    ChevronRight, 
    Eye, 
    EyeOff,
    ArrowUpDown,
    RefreshCw,
    FileText,
    BarChart3,
    AlertCircle,
    CheckCircle,
    XCircle,
    Users,
    Settings,
    Activity
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';

type Partner = { id: number; name: string };
type User = { name: string; email: string; partner?: Partner | null };
type Product = { name: string };
type Order = { id: number; reference: string };
type Expense = { id: number; description: string | null; amount: number; expense_date: string };
type PartnerRemittance = {
    id: number;
    partner_id: number;
    date_from: string;
    date_to: string;
    amount: number;
};
type DriverPayment = {
    id: number;
    driver_id: number;
    period_start: string;
    period_end: string;
    amount: number;
    payment_type: string;
    driver?: { id: number; name: string } | null;
};

type AuditLog = {
    id: number;
    action_type: string;
    old_value: Record<string, unknown> | null;
    new_value: Record<string, unknown> | null;
    created_at: string;
    actor_partner_name?: string | null;
    actor?: User | null;
    partner?: Partner | null;
    product?: Product | null;
    order?: Order | null;
    expense?: Expense | null;
    partner_remittance?: PartnerRemittance | null;
    driver_payment?: DriverPayment | null;
};

type AuditLogsPageProps = {
    logs: {
        data: AuditLog[];
        meta: {
            current_page: number;
            last_page: number;
            total: number;
        };
    };
    partners: Partner[];
    filters: {
        partner_id: number | string | null;
        module: string | null;
        action_type: string | null;
        date_from: string | null;
        date_to: string | null;
        q?: string | null;
        sort?: string | null;
        direction?: 'asc' | 'desc';
    };
    actionTypes: Record<string, string>;
    isAdmin: boolean;
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Historique', href: '/historique-produits-stocks' },
];

const modules: { value: string; label: string; icon: React.ReactNode }[] = [
    { value: '', label: 'Tous les modules', icon: <BarChart3 className="size-4" /> },
    { value: 'produits', label: 'Produits', icon: <Package className="size-4" /> },
    { value: 'stocks', label: 'Stocks', icon: <Package className="size-4" /> },
    { value: 'depenses', label: 'Dépenses', icon: <CreditCard className="size-4" /> },
    { value: 'commandes', label: 'Commandes', icon: <FileText className="size-4" /> },
    { value: 'versements', label: 'Versements', icon: <CreditCard className="size-4" /> },
    { value: 'paiements_livreurs', label: 'Paiements livreurs', icon: <Truck className="size-4" /> },
];

function entityLabel(log: AuditLog): string {
    if (log.order?.reference) return `Commande ${log.order.reference}`;
    if (log.action_type?.startsWith('order_') && log.old_value && typeof log.old_value === 'object' && 'reference' in log.old_value) {
        return `Commande ${String((log.old_value as { reference?: string }).reference ?? '')}`;
    }
    if (log.expense) {
        const desc = log.expense.description?.trim();
        const amount = Number(log.expense.amount).toLocaleString('fr-FR');
        return desc ? `${desc} (${amount} F CFA)` : `${amount} F CFA`;
    }
    if (log.action_type?.startsWith('expense_') && log.old_value && typeof log.old_value === 'object' && ('amount' in log.old_value || 'description' in log.old_value)) {
        const o = log.old_value as { amount?: number; description?: string };
        const amount = o.amount != null ? Number(o.amount).toLocaleString('fr-FR') + ' F CFA' : '';
        const desc = o.description?.trim();
        return desc ? `${desc}${amount ? ` (${amount})` : ''}` : amount || 'Dépense';
    }
    if (log.partner_remittance) {
        const r = log.partner_remittance;
        const from = typeof r.date_from === 'string' ? r.date_from.slice(0, 10) : '';
        const to = typeof r.date_to === 'string' ? r.date_to.slice(0, 10) : '';
        const amount = Number(r.amount).toLocaleString('fr-FR');
        return `Versement ${from} → ${to} : ${amount} F CFA`;
    }
    if (log.driver_payment) {
        const p = log.driver_payment;
        const driverName = p.driver?.name ?? `Livreur #${p.driver_id}`;
        const amount = Number(p.amount).toLocaleString('fr-FR');
        return `Paiement ${driverName} : ${amount} F CFA`;
    }
    if (log.product?.name) return log.product.name;
    return '—';
}

const defaultLogs = {
    data: [] as AuditLog[],
    meta: { current_page: 1, last_page: 1, total: 0 },
};

function normalizeLogsPayload(logs: unknown): {
    data: AuditLog[];
    meta: { current_page: number; last_page: number; total: number };
} {
    if (logs == null || typeof logs !== 'object') {
        return defaultLogs;
    }
    const o = logs as Record<string, unknown>;
    const data = Array.isArray(o.data) ? o.data as AuditLog[] : defaultLogs.data;
    const meta = (o.meta && typeof o.meta === 'object' && o.meta !== null)
        ? {
            current_page: Number((o.meta as Record<string, unknown>).current_page) || 1,
            last_page: Number((o.meta as Record<string, unknown>).last_page) || 1,
            total: Number((o.meta as Record<string, unknown>).total) || 0,
          }
        : {
            current_page: Number(o.current_page) || 1,
            last_page: Number(o.last_page) || 1,
            total: Number(o.total) || 0,
          };
    return { data, meta };
}

export default function AuditLogsIndex(props: AuditLogsPageProps) {
    const { data: logsData, meta: logsMeta } = normalizeLogsPayload(props.logs);
    const partners = Array.isArray(props.partners) ? props.partners : [];
    const filters = props.filters ?? {};
    const actionTypes = props.actionTypes ?? {};
    const isAdmin = Boolean(props.isAdmin);
    const safeActionTypes = actionTypes && typeof actionTypes === 'object' ? actionTypes : {};

    const [partnerId, setPartnerId] = useState(
        filters.partner_id != null && filters.partner_id !== '' ? String(filters.partner_id) : 'all',
    );
    const [module, setModule] = useState(filters.module ?? '');
    const [actionType, setActionType] = useState(filters.action_type ?? 'all');
    const [dateFrom, setDateFrom] = useState(filters.date_from ?? '');
    const [dateTo, setDateTo] = useState(filters.date_to ?? '');
    const [search, setSearch] = useState(filters.q ?? '');
    const [sortKey, setSortKey] = useState(filters.sort ?? 'created_at');
    const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>(
        filters.direction ?? 'desc',
    );
    const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({});
    const [showAllRows, setShowAllRows] = useState(false);

    const exportUrl = useMemo(() => {
        const params = new URLSearchParams();
        if (partnerId !== 'all') params.set('partner_id', partnerId);
        if (actionType !== 'all') params.set('action_type', actionType);
        if (dateFrom) params.set('date_from', dateFrom);
        if (dateTo) params.set('date_to', dateTo);
        const query = params.toString();
        return `/historique-produits-stocks/export${query ? `?${query}` : ''}`;
    }, [actionType, dateFrom, dateTo, partnerId]);

    const exportExcelUrl = useMemo(() => {
        const params = new URLSearchParams();
        if (partnerId !== 'all') params.set('partner_id', partnerId);
        if (module) params.set('module', module);
        if (actionType !== 'all') params.set('action_type', actionType);
        if (dateFrom) params.set('date_from', dateFrom);
        if (dateTo) params.set('date_to', dateTo);
        const query = params.toString();
        return `/historique-produits-stocks/export-excel${query ? `?${query}` : ''}`;
    }, [actionType, dateFrom, dateTo, partnerId, module]);

    const buildQueryParams = (page?: number) => ({
        partner_id: partnerId !== 'all' ? partnerId : undefined,
        module: module || undefined,
        action_type: actionType !== 'all' ? actionType : undefined,
        date_from: dateFrom || undefined,
        date_to: dateTo || undefined,
        q: search || undefined,
        sort: sortKey,
        direction: sortDirection,
        page,
    });

    const handleSort = (key: string) => {
        const nextDirection =
            sortKey === key && sortDirection === 'asc' ? 'desc' : 'asc';
        setSortKey(key);
        setSortDirection(nextDirection);
        router.get('/historique-produits-stocks', buildQueryParams(), {
            preserveState: true,
            replace: true,
        });
    };

    const applyFilters = (page?: number) => {
        router.get(
            '/historique-produits-stocks',
            buildQueryParams(page),
            { preserveState: true, replace: true },
        );
    };

    const isFirstFilterRun = useRef(true);
    const [searchDebounced, setSearchDebounced] = useState(filters.q ?? '');

    useEffect(() => {
        const t = setTimeout(() => setSearchDebounced(search), 400);
        return () => clearTimeout(t);
    }, [search]);

    useEffect(() => {
        if (isFirstFilterRun.current) {
            isFirstFilterRun.current = false;
            return;
        }
        applyFilters(1);
    }, [partnerId, module, actionType, dateFrom, dateTo, searchDebounced]);

    const toggleAllRows = () => {
        if (showAllRows) {
            setExpandedRows({});
        } else {
            const allExpanded: Record<number, boolean> = {};
            logsData.forEach(log => {
                allExpanded[log.id] = true;
            });
            setExpandedRows(allExpanded);
        }
        setShowAllRows(!showAllRows);
    };

    const getActionTypeColor = (actionType: string) => {
        if (actionType.includes('create')) return 'green';
        if (actionType.includes('update')) return 'blue';
        if (actionType.includes('delete')) return 'red';
        if (actionType.includes('status')) return 'amber';
        return 'gray';
    };

    const formatActionType = (actionType: string): string => {
        return safeActionTypes[actionType] || actionType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Historique des actions" />
            <div className="flex flex-col gap-6 p-4 md:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
                {/* En-tête avec thème noir */}
                <div className="rounded-xl border border-gray-200 bg-gradient-to-r from-gray-900 to-black p-6 dark:border-gray-800 shadow-lg">
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                        <div>
                            <h1 className="text-3xl font-bold tracking-tight text-white">
                                📜 Historique des Actions
                            </h1>
                            <p className="mt-2 text-gray-300">
                                Suivez toutes les modifications, créations et suppressions dans votre système
                            </p>
                        </div>
                        <div className="flex flex-wrap gap-3">
                            <Button
                                type="button"
                                variant="outline"
                                className="border-gray-600 bg-gray-800/50 text-white hover:bg-gray-700 hover:text-white"
                                onClick={() => applyFilters()}
                            >
                                <RefreshCw className="mr-2 size-4" />
                                Actualiser
                            </Button>
                        </div>
                    </div>
                </div>

                {/* Section Quick Actions */}
                <div className="grid gap-4 sm:grid-cols-4">
                    <Button
                        variant="outline"
                        className="flex flex-col items-center justify-center gap-2 h-24 border-gray-200 bg-white hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-900 dark:hover:bg-gray-800"
                        onClick={toggleAllRows}
                    >
                        <div className="flex size-12 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/30">
                            {showAllRows ? (
                                <EyeOff className="size-6 text-blue-600 dark:text-blue-400" />
                            ) : (
                                <Eye className="size-6 text-blue-600 dark:text-blue-400" />
                            )}
                        </div>
                        <span className="font-medium">
                            {showAllRows ? 'Masquer tous' : 'Voir tous'}
                        </span>
                    </Button>
                    <Button
                        variant="outline"
                        className="flex flex-col items-center justify-center gap-2 h-24 border-gray-200 bg-white hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-900 dark:hover:bg-gray-800"
                        asChild
                    >
                        <a href={exportUrl}>
                            <div className="flex size-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/30">
                                <Download className="size-6 text-green-600 dark:text-green-400" />
                            </div>
                            <span className="font-medium">Exporter CSV</span>
                        </a>
                    </Button>
                    <Button
                        variant="outline"
                        className="flex flex-col items-center justify-center gap-2 h-24 border-gray-200 bg-white hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-900 dark:hover:bg-gray-800"
                        asChild
                    >
                        <a href={exportExcelUrl}>
                            <div className="flex size-12 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30">
                                <FileSpreadsheet className="size-6 text-emerald-600 dark:text-emerald-400" />
                            </div>
                            <span className="font-medium">Exporter Excel</span>
                        </a>
                    </Button>
                    <Button
                        variant="outline"
                        className="flex flex-col items-center justify-center gap-2 h-24 border-gray-200 bg-white hover:bg-gray-50 dark:border-gray-800 dark:bg-gray-900 dark:hover:bg-gray-800"
                        onClick={() => {
                            setPartnerId('all');
                            setModule('');
                            setActionType('all');
                            setDateFrom('');
                            setDateTo('');
                            setSearch('');
                            setSearchDebounced('');
                        }}
                    >
                        <div className="flex size-12 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30">
                            <Filter className="size-6 text-red-600 dark:text-red-400" />
                        </div>
                        <span className="font-medium">Réinitialiser</span>
                    </Button>
                </div>

                {/* Section Filtres */}
                <Card className="border-blue-200 bg-white shadow-lg dark:border-blue-800 dark:bg-gray-900">
                    <CardHeader className="border-b border-blue-100 dark:border-blue-900">
                        <div className="flex items-center justify-between">
                            <CardTitle className="flex items-center gap-2 text-blue-900 dark:text-blue-100">
                                <Filter className="size-5" />
                                Filtres Avancés
                            </CardTitle>
                            <Badge className="bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-300">
                                {logsMeta.total} actions
                            </Badge>
                        </div>
                    </CardHeader>
                    <CardContent className="pt-6">
                        <div className="grid gap-4 md:grid-cols-5">
                            {/* Barre de recherche */}
                            <div className="md:col-span-5">
                                <div className="relative">
                                    <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-gray-400" />
                                    <Input
                                        placeholder="Rechercher (acteur, partenaire, produit, action...)"
                                        className="pl-10 border-gray-300 dark:border-gray-700"
                                        value={search}
                                        onChange={(event) => setSearch(event.target.value)}
                                        onKeyDown={(e) => e.key === 'Enter' && setSearchDebounced(search)}
                                    />
                                </div>
                            </div>

                            {/* Partenaire */}
                            {(isAdmin || (partners && partners.length > 0)) ? (
                                <div className="space-y-2">
                                    <Label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                                        <Building className="size-4" />
                                        Partenaire
                                    </Label>
                                    <Select
                                        value={partnerId}
                                        onValueChange={(value) => setPartnerId(value)}
                                    >
                                        <SelectTrigger className="border-gray-300 dark:border-gray-700">
                                            <SelectValue placeholder="Sélectionnez un partenaire" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all" className="flex items-center gap-2">
                                                <Users className="size-4" />
                                                Tous les partenaires
                                            </SelectItem>
                                            {partners.map((partner) => (
                                                <SelectItem
                                                    key={partner.id}
                                                    value={String(partner.id)}
                                                    className="flex items-center gap-2"
                                                >
                                                    <Building className="size-4" />
                                                    {partner.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            ) : null}

                            {/* Module */}
                            <div className="space-y-2">
                                <Label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                                    <Settings className="size-4" />
                                    Module
                                </Label>
                                <Select value={module || 'all'} onValueChange={(v) => setModule(v === 'all' ? '' : v)}>
                                    <SelectTrigger className="border-gray-300 dark:border-gray-700">
                                        <SelectValue placeholder="Sélectionnez un module" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {modules.map((m) => (
                                            <SelectItem key={m.value || 'all'} value={m.value || 'all'} className="flex items-center gap-2">
                                                {m.icon}
                                                {m.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Type d'action */}
                            <div className="space-y-2">
                                <Label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                                    <Activity className="size-4" />
                                    Type d'action
                                </Label>
                                <Select
                                    value={actionType}
                                    onValueChange={(value) => setActionType(value)}
                                >
                                    <SelectTrigger className="border-gray-300 dark:border-gray-700">
                                        <SelectValue placeholder="Type d'action" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all" className="flex items-center gap-2">
                                            <History className="size-4" />
                                            Tous les types
                                        </SelectItem>
                                        {Object.entries(safeActionTypes).map(([key, label]) => (
                                            <SelectItem 
                                                key={key} 
                                                value={key}
                                                className={`flex items-center gap-2 ${
                                                    getActionTypeColor(key) === 'green' ? 'text-green-600 dark:text-green-400' :
                                                    getActionTypeColor(key) === 'blue' ? 'text-blue-600 dark:text-blue-400' :
                                                    getActionTypeColor(key) === 'red' ? 'text-red-600 dark:text-red-400' :
                                                    'text-gray-600 dark:text-gray-400'
                                                }`}
                                            >
                                                {getActionTypeColor(key) === 'green' && <CheckCircle className="size-4" />}
                                                {getActionTypeColor(key) === 'blue' && <Settings className="size-4" />}
                                                {getActionTypeColor(key) === 'red' && <XCircle className="size-4" />}
                                                {getActionTypeColor(key) === 'amber' && <AlertCircle className="size-4" />}
                                                {label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>

                            {/* Date début */}
                            <div className="space-y-2">
                                <Label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                                    <Calendar className="size-4" />
                                    Date début
                                </Label>
                                <Input
                                    type="date"
                                    className="border-gray-300 dark:border-gray-700"
                                    value={dateFrom}
                                    onChange={(event) => setDateFrom(event.target.value)}
                                />
                            </div>

                            {/* Date fin */}
                            <div className="space-y-2">
                                <Label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                                    <Calendar className="size-4" />
                                    Date fin
                                </Label>
                                <Input
                                    type="date"
                                    className="border-gray-300 dark:border-gray-700"
                                    value={dateTo}
                                    onChange={(event) => setDateTo(event.target.value)}
                                />
                            </div>

                            <p className="md:col-span-5 pt-2 text-sm text-gray-500 dark:text-gray-400">
                                Les filtres sont appliqués automatiquement.
                            </p>
                        </div>
                    </CardContent>
                </Card>

                {/* Section Historique */}
                <Card className="border-gray-200 bg-white shadow-lg dark:border-gray-800 dark:bg-gray-900">
                    <CardHeader className="border-b border-gray-200 dark:border-gray-800">
                        <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                            <div className="flex items-center gap-3">
                                <div className="flex size-10 items-center justify-center rounded-full bg-purple-100 dark:bg-purple-900/30">
                                    <History className="size-5 text-purple-600 dark:text-purple-400" />
                                </div>
                                <div>
                                    <CardTitle className="text-xl font-bold text-gray-900 dark:text-white">
                                        Historique des Actions
                                    </CardTitle>
                                    <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
                                        {logsMeta.total} actions • Page {logsMeta.current_page} sur {logsMeta.last_page}
                                    </p>
                                </div>
                            </div>
                            <div className="flex flex-wrap items-center gap-3">
                                <Badge variant="outline" className="bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300">
                                    Tri: {sortDirection === 'asc' ? '↑' : '↓'} {sortKey === 'created_at' ? 'Date' : sortKey}
                                </Badge>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                                <thead className="bg-gray-100 dark:bg-gray-800">
                                    <tr className="text-left text-gray-700 dark:text-gray-300">
                                        <th className="px-4 py-3 font-medium">
                                            <button
                                                type="button"
                                                className="flex items-center gap-2 hover:text-gray-900 dark:hover:text-white"
                                                onClick={() => handleSort('created_at')}
                                            >
                                                <Calendar className="size-4" />
                                                Date
                                                <ArrowUpDown className={`size-3 ${
                                                    sortKey === 'created_at' 
                                                        ? sortDirection === 'asc' 
                                                            ? 'text-green-600 dark:text-green-400' 
                                                            : 'text-red-600 dark:text-red-400'
                                                        : 'text-gray-400'
                                                }`} />
                                            </button>
                                        </th>
                                        <th className="px-4 py-3 font-medium">
                                            <button
                                                type="button"
                                                className="flex items-center gap-2 hover:text-gray-900 dark:hover:text-white"
                                                onClick={() => handleSort('action_type')}
                                            >
                                                <Activity className="size-4" />
                                                Action
                                                <ArrowUpDown className={`size-3 ${
                                                    sortKey === 'action_type' 
                                                        ? sortDirection === 'asc' 
                                                            ? 'text-green-600 dark:text-green-400' 
                                                            : 'text-red-600 dark:text-red-400'
                                                        : 'text-gray-400'
                                                }`} />
                                            </button>
                                        </th>
                                        <th className="px-4 py-3 font-medium">
                                            <button
                                                type="button"
                                                className="flex items-center gap-2 hover:text-gray-900 dark:hover:text-white"
                                                onClick={() => handleSort('partner')}
                                            >
                                                <Building className="size-4" />
                                                Partenaire
                                                <ArrowUpDown className={`size-3 ${
                                                    sortKey === 'partner' 
                                                        ? sortDirection === 'asc' 
                                                            ? 'text-green-600 dark:text-green-400' 
                                                            : 'text-red-600 dark:text-red-400'
                                                        : 'text-gray-400'
                                                }`} />
                                            </button>
                                        </th>
                                        <th className="px-4 py-3 font-medium">
                                            <button
                                                type="button"
                                                className="flex items-center gap-2 hover:text-gray-900 dark:hover:text-white"
                                                onClick={() => handleSort('product')}
                                            >
                                                <Package className="size-4" />
                                                Entité
                                                <ArrowUpDown className={`size-3 ${
                                                    sortKey === 'product' 
                                                        ? sortDirection === 'asc' 
                                                            ? 'text-green-600 dark:text-green-400' 
                                                            : 'text-red-600 dark:text-red-400'
                                                        : 'text-gray-400'
                                                }`} />
                                            </button>
                                        </th>
                                        <th className="px-4 py-3 font-medium">
                                            <button
                                                type="button"
                                                className="flex items-center gap-2 hover:text-gray-900 dark:hover:text-white"
                                                onClick={() => handleSort('actor')}
                                            >
                                                <User className="size-4" />
                                                Acteur
                                                <ArrowUpDown className={`size-3 ${
                                                    sortKey === 'actor' 
                                                        ? sortDirection === 'asc' 
                                                            ? 'text-green-600 dark:text-green-400' 
                                                            : 'text-red-600 dark:text-red-400'
                                                        : 'text-gray-400'
                                                }`} />
                                            </button>
                                        </th>
                                        <th className="px-4 py-3 font-medium text-right">Détails</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {logsData.length === 0 ? (
                                        <tr>
                                            <td colSpan={6} className="px-4 py-8 text-center">
                                                <div className="mx-auto max-w-sm space-y-4">
                                                    <div className="mx-auto flex size-16 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
                                                        <History className="size-8 text-gray-400" />
                                                    </div>
                                                    <div>
                                                        <p className="text-lg font-semibold text-gray-900 dark:text-white">
                                                            Aucune action trouvée
                                                        </p>
                                                        <p className="mt-1 text-gray-600 dark:text-gray-400">
                                                            Aucune action ne correspond à vos critères de recherche.
                                                        </p>
                                                    </div>
                                                    <Button
                                                        onClick={() => {
                                                            setPartnerId('all');
                                                            setModule('');
                                                            setActionType('all');
                                                            setDateFrom('');
                                                            setDateTo('');
                                                            setSearch('');
                                                            applyFilters();
                                                        }}
                                                        className="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800"
                                                    >
                                                        Réinitialiser les filtres
                                                    </Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : (
                                        logsData.map((log, index) => (
                                            <Fragment key={log.id}>
                                                <tr className={`border-t border-gray-200 dark:border-gray-800 transition-all hover:bg-gray-50 dark:hover:bg-gray-800/50 ${
                                                    index % 2 === 0 ? 'bg-white dark:bg-gray-900' : 'bg-gray-50/50 dark:bg-gray-900/50'
                                                }`}>
                                                    <td className="px-4 py-3">
                                                        <div className="font-medium text-gray-900 dark:text-white">
                                                            {new Date(log.created_at).toLocaleDateString('fr-FR', {
                                                                day: '2-digit',
                                                                month: '2-digit',
                                                                year: 'numeric',
                                                                hour: '2-digit',
                                                                minute: '2-digit'
                                                            })}
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <Badge className={`${
                                                            getActionTypeColor(log.action_type) === 'green' 
                                                                ? 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300' :
                                                            getActionTypeColor(log.action_type) === 'blue' 
                                                                ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-300' :
                                                            getActionTypeColor(log.action_type) === 'red' 
                                                                ? 'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300' :
                                                            getActionTypeColor(log.action_type) === 'amber'
                                                                ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300'
                                                                : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300'
                                                        } font-medium`}>
                                                            {formatActionType(log.action_type)}
                                                        </Badge>
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <div className="flex items-center gap-2">
                                                            <Building className="size-4 text-gray-400" />
                                                            <span className="font-medium text-gray-900 dark:text-white">
                                                                {log.partner?.name || '-'}
                                                            </span>
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3 max-w-[200px]">
                                                        <div className="flex items-center gap-2">
                                                            {log.order && <FileText className="size-4 text-blue-400" />}
                                                            {log.expense && <CreditCard className="size-4 text-red-400" />}
                                                            {log.product && <Package className="size-4 text-green-400" />}
                                                            {log.partner_remittance && <CreditCard className="size-4 text-purple-400" />}
                                                            {log.driver_payment && <Truck className="size-4 text-amber-400" />}
                                                            <span 
                                                                className="truncate font-medium text-gray-900 dark:text-white" 
                                                                title={entityLabel(log)}
                                                            >
                                                                {entityLabel(log)}
                                                            </span>
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <div className="flex flex-col gap-0.5">
                                                            <div className="flex items-center gap-2">
                                                                <User className="size-4 shrink-0 text-gray-400" />
                                                                <span className="text-gray-900 dark:text-white">
                                                                    {log.actor?.name || '-'}
                                                                </span>
                                                            </div>
                                                            {log.actor?.email && (
                                                                <span className="text-xs text-gray-500 dark:text-gray-400 pl-6">
                                                                    {log.actor.email}
                                                                </span>
                                                            )}
                                                            {(log.actor_partner_name ?? log.actor?.partner?.name) && (
                                                                <span className="text-xs font-medium text-blue-600 dark:text-blue-400 pl-6">
                                                                    {log.actor_partner_name ?? log.actor?.partner?.name}
                                                                </span>
                                                            )}
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-3 text-right">
                                                        <Button
                                                            size="sm"
                                                            variant="ghost"
                                                            className="h-8 w-8 p-0 text-blue-600 hover:bg-blue-50 hover:text-blue-700 dark:text-blue-400 dark:hover:bg-blue-900/30"
                                                            onClick={() =>
                                                                setExpandedRows((prev) => ({
                                                                    ...prev,
                                                                    [log.id]: !prev[log.id],
                                                                }))
                                                            }
                                                            title={expandedRows[log.id] ? "Masquer les détails" : "Voir les détails"}
                                                        >
                                                            {expandedRows[log.id] ? (
                                                                <ChevronDown className="size-4" />
                                                            ) : (
                                                                <ChevronRight className="size-4" />
                                                            )}
                                                        </Button>
                                                    </td>
                                                </tr>
                                                {expandedRows[log.id] && (
                                                    <tr className="border-t bg-gray-50 dark:bg-gray-900/50">
                                                        <td colSpan={6} className="px-4 py-4">
                                                            <div className="space-y-4">
                                                                <div className="flex items-center gap-2">
                                                                    <Settings className="size-5 text-gray-600 dark:text-gray-400" />
                                                                    <h4 className="font-semibold text-gray-900 dark:text-white">
                                                                        Détails des modifications
                                                                    </h4>
                                                                </div>
                                                                <div className="grid gap-4 md:grid-cols-2">
                                                                    <div className="space-y-2">
                                                                        <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                                                            <div className="flex items-center gap-2">
                                                                                <History className="size-4 text-amber-600" />
                                                                                Ancienne valeur
                                                                            </div>
                                                                        </Label>
                                                                        <div className="rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
                                                                            <pre className="max-h-48 overflow-auto text-xs text-gray-800 dark:text-gray-200">
                                                                                {log.old_value
                                                                                    ? JSON.stringify(log.old_value, null, 2)
                                                                                    : '—'}
                                                                            </pre>
                                                                        </div>
                                                                    </div>
                                                                    <div className="space-y-2">
                                                                        <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                                                            <div className="flex items-center gap-2">
                                                                                <RefreshCw className="size-4 text-green-600" />
                                                                                Nouvelle valeur
                                                                            </div>
                                                                        </Label>
                                                                        <div className="rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
                                                                            <pre className="max-h-48 overflow-auto text-xs text-gray-800 dark:text-gray-200">
                                                                                {log.new_value
                                                                                    ? JSON.stringify(log.new_value, null, 2)
                                                                                    : '—'}
                                                                            </pre>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                )}
                                            </Fragment>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        {logsMeta.last_page > 1 && (
                            <div className="border-t border-gray-200 bg-gray-50 px-4 py-3 dark:border-gray-800 dark:bg-gray-900">
                                <div className="flex flex-col items-center justify-between gap-4 sm:flex-row">
                                    <div className="text-sm text-gray-600 dark:text-gray-400">
                                        Affichage de <span className="font-semibold text-gray-900 dark:text-white">
                                            {Math.min((logsMeta.current_page - 1) * 10 + 1, logsMeta.total)}
                                        </span> à{' '}
                                        <span className="font-semibold text-gray-900 dark:text-white">
                                            {Math.min(logsMeta.current_page * 10, logsMeta.total)}
                                        </span>{' '}
                                        sur <span className="font-semibold text-gray-900 dark:text-white">{logsMeta.total}</span> actions
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            className="border-gray-300 text-gray-700 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
                                            disabled={logsMeta.current_page <= 1}
                                            onClick={() =>
                                                router.get(
                                                    '/historique-produits-stocks',
                                                    buildQueryParams(logsMeta.current_page - 1),
                                                    { preserveState: true, replace: true },
                                                )
                                            }
                                        >
                                            Précédent
                                        </Button>
                                        <div className="flex items-center gap-1">
                                            {Array.from({ length: Math.min(5, logsMeta.last_page) }, (_, i) => {
                                                const page = i + 1;
                                                return (
                                                    <Button
                                                        key={page}
                                                        size="sm"
                                                        variant={logsMeta.current_page === page ? "default" : "outline"}
                                                        className={`h-8 w-8 p-0 ${
                                                            logsMeta.current_page === page 
                                                                ? 'bg-blue-600 text-white hover:bg-blue-700' 
                                                                : 'border-gray-300 text-gray-700 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800'
                                                        }`}
                                                        onClick={() =>
                                                            router.get(
                                                                '/historique-produits-stocks',
                                                                buildQueryParams(page),
                                                                { preserveState: true, replace: true },
                                                            )
                                                        }
                                                    >
                                                        {page}
                                                    </Button>
                                                );
                                            })}
                                            {logsMeta.last_page > 5 && (
                                                <span className="px-2 text-sm text-gray-500">...</span>
                                            )}
                                        </div>
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            className="border-gray-300 text-gray-700 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
                                            disabled={logsMeta.current_page >= logsMeta.last_page}
                                            onClick={() =>
                                                router.get(
                                                    '/historique-produits-stocks',
                                                    buildQueryParams(logsMeta.current_page + 1),
                                                    { preserveState: true, replace: true },
                                                )
                                            }
                                        >
                                            Suivant
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}