import React, { useState, useMemo } 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';

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 {
    connectionHistory?: ConnectionSession[];
}

export default function ConnectionHistoryTable({ connectionHistory = [] }: ConnectionHistoryTableProps) {
    const table = useTable({defaultOrderBy : HEAD_CELLS[0].id});
    const [order, setOrder] = useState<'asc' | 'desc'>('desc');
    const [orderBy, setOrderBy] = useState<keyof ConnectionHistoryType>('date');
    const handleSort = (property: keyof ConnectionHistoryType) => {
        setOrder((prev) => (orderBy === property && prev === 'asc' ? 'desc' : 'asc'));
        setOrderBy(property);
    };

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

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

    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 = (minutes: number | null) => minutes
        ? `${Math.floor(minutes / 60)}h ${minutes % 60}min`
        : 'N/A';

    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={connectionHistory.length}
            page={table.page}
            rowsPerPage={table.rowsPerPage}
            onPageChange={table.onChangePage}
          />
        </Box>
                </Box>
    );
}