import React, { useState, useMemo, useEffect } from 'react';
import {
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    Typography,
    Box,
} from '@mui/material';
import { faHistory } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import { ConnectionSession } from '@/shared/types/agent';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';
import { HistoryStyledRow } from '../../styles';
import TablePaginationCustom from '@/shared/components/table/table-pagination-custom';
import useTable from '@/shared/components/table/use-tablets';
import { UserConnectionHistoryDto } from '@/shared/types/client';
import { useAuthStore } from '@/shared/api/stores/authStore';

type ConnectionHistoryType = {
    id: string;
    date: string;
    startTime: string;
    endTime: string | null;
    duration: number | null;
};

const HEAD_CELLS = [
    { id: 'date', label: 'Date', align: 'left' as const },
    { id: 'startTime', label: 'Heure de connexion', align: 'left' as const },
    { id: 'endTime', label: 'Heure de déconnexion', align: 'left' as const },
    { id: 'duration', label: 'Durée', align: 'left' as const },
];

interface ConnectionHistoryTableProps {
    userId: string;
}

export default function ConnectionHistoryTable({ userId }: ConnectionHistoryTableProps) {
    const [data, setData] = useState<ConnectionHistoryType[]>([]);
    const { getUserHistory } = useAuthStore();
    const table = useTable({ defaultOrderBy: HEAD_CELLS[0].id });
    const [order, setOrder] = useState<'asc' | 'desc'>('desc');
    const [orderBy, setOrderBy] = useState<keyof ConnectionHistoryType>('date');
    const [totalCount, setTotalCount] = useState(0);

    const mapOrderByToApiField = (column: keyof ConnectionHistoryType): string => {
        switch (column) {
            case 'date':
            case 'startTime':
                return 'loginDateTime';
            case 'endTime':
                return 'logoutDateTime';
            case 'duration':
                return 'duration';
            default:
                return 'loginDateTime';
        }
    };

    // Fonction pour charger les données
    const fetchData = async () => {
        try {
            const response = await getUserHistory({
                userId,
                page: table.page,
                size: table.rowsPerPage,
                sortBy: mapOrderByToApiField(orderBy),
                direction: order
            });
            
            const transformed = response.content.map((session): ConnectionHistoryType => {
                const startTime = new Date(session.loginDateTime);
                const endTime = session.logoutDateTime ? new Date(session.logoutDateTime) : null;

                return {
                    id: session.id.toString(),
                    date: session.loginDateTime,
                    startTime: startTime.toISOString(),
                    endTime: endTime ? endTime.toISOString() : null,
                    duration: Number(session.duration),
                };
            });
            setData(transformed);
            setTotalCount(response.totalElements);
        } catch (error) {
            console.error("Erreur lors de la récupération de l'historique :", error);
        }
    };

    // useEffect pour recharger les données quand les paramètres changent
    useEffect(() => {
        fetchData();
    }, [userId, order, orderBy, table.page, table.rowsPerPage]);

    const handleSort = (property: keyof ConnectionHistoryType) => {
        setOrder((prev) => (orderBy === property && prev === 'asc' ? 'desc' : 'asc'));
        setOrderBy(property);
    };

    const transformedData: ConnectionHistoryType[] = useMemo(() =>
        data.map((session) => {
            const startTime = new Date(session.startTime);
            const endTime = session.endTime ? new Date(session.endTime) : null;

            return {
                id: session.id,
                date: session.endTime ? new Date(session.endTime).toISOString() : '',
                startTime: startTime.toISOString(),
                endTime: endTime ? endTime.toISOString() : null,
                duration: session.duration,
            };
        }),
        [data]
    );

    const sortedData = useMemo(() =>
        [...transformedData].sort((a, b) => {
            if (orderBy) {
                const aValue = a[orderBy];
                const bValue = b[orderBy];

                if (aValue === null) return order === 'asc' ? -1 : 1;
                if (bValue === null) return order === 'asc' ? 1 : -1;

                return (String(aValue) < String(bValue) ? -1 : 1) * (order === 'asc' ? 1 : -1);
            }
            return 0;
        }),
        [transformedData, order, orderBy]
    );

    const formatDate = (isoDate: string) => new Date(isoDate).toLocaleDateString('fr-FR');
    const formatTime = (isoDate: string | null) => isoDate
        ? new Date(isoDate).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })
        : 'En cours';
    const formatDuration = (seconds: number | null) => {
        if (seconds === null || isNaN(seconds)) return 'En cours';

        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        const s = seconds % 60;

        return `${h}h ${m}min ${s}s`;
    };

    // Wrapper pour convertir le type d'événement
    const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        table.onChangeRowsPerPage({
            target: { value: event.target.value }
        } as any);
    };

    return (
        <Box sx={{ width: '100%', mb: '20px' }}>
            <Typography
                variant="h5"
                sx={{
                    my: 2,
                    color: 'primary.main',
                    fontWeight: (theme) => theme.typography.fontWeightBold,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 1
                }}
            >
                <FontAwesome icon={faHistory} width={20} color="primary.main" />
                Historique de connexion
            </Typography>

            <TableContainer>
                <Table sx={{ minWidth: 650, borderRadius: '12px' }}>
                    <TableHead sx={{ backgroundColor: 'white' }}>
                        <HistoryStyledRow>
                            {HEAD_CELLS.map((headCell) => (
                                <TableCell
                                    sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}
                                    key={headCell.id}
                                    align={headCell.align}
                                    sortDirection={orderBy === headCell.id ? order : false}
                                >
                                    <CustomTableSortLabel
                                        active={orderBy === headCell.id}
                                        direction={orderBy === headCell.id ? order : 'asc'}
                                        orderBy={orderBy}
                                        order={order}
                                        onSort={() => handleSort(headCell.id as keyof ConnectionHistoryType)}
                                    >
                                        {headCell.label}
                                    </CustomTableSortLabel>
                                </TableCell>
                            ))}
                        </HistoryStyledRow>
                    </TableHead>
                    <TableBody>
                        {sortedData.map((session) => (
                            <HistoryStyledRow key={session.id}>
                                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 } }}>
                                    {formatDate(session.date)}
                                </TableCell>
                                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 } }}>
                                    {formatTime(session.startTime)}
                                </TableCell>
                                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 } }}>
                                    {formatTime(session.endTime)}
                                </TableCell>
                                <TableCell sx={{ py: 0, px: { xs: 1, xl: 2 } }}>
                                    {formatDuration(session.duration)}
                                </TableCell>
                            </HistoryStyledRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
            <Box sx={{ flexGrow: 0 }}>
                <TablePaginationCustom
                    count={totalCount}
                    page={table.page}
                    rowsPerPage={table.rowsPerPage}
                    onPageChange={table.onChangePage}
                    onRowsPerPageChange={handleRowsPerPageChange}
                />
            </Box>
        </Box>
    );
}