'use client';

import React, { useCallback, useState } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  useMediaQuery,
  useTheme,
  Stack,
  Card,
  alpha,
} from '@mui/material';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import SecurityIcon from '@mui/icons-material/Security';

// Hooks & Utils
import { useTableManager } from '@/hooks/use-table-manager';
import _sessions, { DEFAULT_TABLE_HEAD } from '@/shared/_mock/_session';
import { ISession } from '@/shared/types/session';
import SessionTableRow from '../components/session-history-row';
import { getDeviceDisplay, getDeviceIcon, getTimeAgo } from '../utils/functions-helpers';
import { HEADER } from '@/layouts/config-layout';
import { InfoBox, StyledTableContainer } from '../../styled-component';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import TablePaginationCustom from '@/shared/components/table/table-pagination-custom';






const sessionConfig = {
  initialData: _sessions,
  defaultTableHead: DEFAULT_TABLE_HEAD,
};

export default function SessionHistoryView() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const [confirmDialog, setConfirmDialog] = useState({
    open: false,
    sessionId: '',
    deviceName: '',
  });

  const {
    table,
    filteredData,
    tableHead,
    notFound,
  } = useTableManager<ISession>(sessionConfig);
  const handleCloseDialog = () => {
    setConfirmDialog({
      open: false,
      sessionId: '',
      deviceName: '',
    });
  };
  const handleDisconnect = useCallback((sessionId: string, deviceName: string) => {
    setConfirmDialog({
      open: true,
      sessionId,
      deviceName,
    });
  }, []);

  const confirmDisconnect = () => {
    setConfirmDialog({
      open: false,
      sessionId: '',
      deviceName: '',
    });
  };

  const renderRow = (row: ISession) => (
    <SessionTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      getDeviceIcon={getDeviceIcon}
      getDeviceDisplay={getDeviceDisplay}
      getTimeAgo={getTimeAgo}
      handleDisconnect={(id) => handleDisconnect(id, getDeviceDisplay(row.device))}
      columns={tableHead.slice(0, -1).map(column => ({ ...column, type: column.type || '' }))}
      isMobile={isMobile}
    />
  );

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP +  16}px)`,
        overflow: 'auto',
        '&::-webkit-scrollbar': {
          width: '8px',
        },
        '&::-webkit-scrollbar-thumb': {
          backgroundColor: 'rgba(0,0,0,0.1)',
          borderRadius: '4px',
        },
        '&::-webkit-scrollbar-track': {
          backgroundColor: 'transparent',
        },
        pb: 2,
        px: 1,
      }}
    >
    <Stack spacing={3}>
      <Card sx={{ p: 3, pb: 5 }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 4 }}>
          <Stack direction="row" alignItems="center" spacing={3}>
            <Box
              sx={{
                width: 80,
                height: 80,
                borderRadius: 2,
                border: `2px solid ${theme.palette.primary.main}`,
                bgcolor: alpha(theme.palette.primary.main, 0.15),
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <SecurityIcon sx={{ fontSize: 40, color: 'primary.main' }} />
            </Box>
            <Box>
              <Typography variant="h4" gutterBottom sx={{ fontWeight: 'semibold' , color: 'primary.main'}}>
                Historique de session
              </Typography>
              
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                Gérez vos sessions actives sur différents appareils
              </Typography>
            </Box>
          </Stack>
        </Stack>

        <InfoBox sx={{  bgcolor: alpha(theme.palette.primary.main, 0.13)}}>
          <InfoOutlinedIcon sx={{ color: 'primary.main' }} />
          <Typography variant="body2" color="primary.main">
            Pour des raisons de sécurité, vous pouvez consulter et gérer toutes vos sessions actives. 
            Si vous ne reconnaissez pas une session, déconnectez-la immédiatement et changez votre mot de passe.
          </Typography>
        </InfoBox>

        <Typography variant="subtitle1" sx={{ mb: 2, fontWeight: 'bold' }}>
          {filteredData.length} session{filteredData.length !== 1 ? 's' : ''} active{filteredData.length !== 1 ? 's' : ''}
        </Typography>

        <StyledTableContainer
        sx={{
          maxHeight: 'calc(100vh - 486px)',
        }}
        >
          <Table sx={{ minWidth: isMobile ? 300 : 650 }}>
            <TableHead>
              <TableRow>
                {tableHead.map((column) =>
                  (column.id === 'location' && isMobile) ? null : (
                    <TableCell key={column.id}>
                      {column.label}
                    </TableCell>
                  )
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredData.map(row => renderRow(row))}
              <ConditionalComponent isValid={notFound}>
                  <TableRow>
                    <TableCell colSpan={tableHead.length} align="center">
                      <Typography variant="body2" sx={{ py: 5, color: 'text.secondary' }}>
                        Aucune session active trouvée
                      </Typography>
                    </TableCell>
                  </TableRow>
                </ConditionalComponent>
            </TableBody>
          </Table>
        </StyledTableContainer>
        <Box sx={{ flexGrow: 0 }}>
          <TablePaginationCustom
            count={filteredData.length}
            page={table.page}
            rowsPerPage={table.rowsPerPage}
            onPageChange={table.onChangePage}
            onRowsPerPageChange={(event: React.ChangeEvent<HTMLInputElement>) => table.onChangeRowsPerPage(event)}
            dense={table.dense}
          />
        </Box>

        <Box sx={{ mt: 3 }}>
          <Typography variant="body2" color="text.secondary">
            * La session actuelle est marquée comme &quot;Actuel&quot; et ne peut pas être déconnectée depuis cet appareil.
          </Typography>
        </Box>
      </Card>
      <ConfirmDialog
  open={confirmDialog.open}
  title="Confirmer la déconnexion"
  content={`Êtes-vous sûr de vouloir déconnecter la session sur "${confirmDialog.deviceName}" ? L'utilisateur devra se reconnecter sur cet appareil.`}
  onConfirm={() => {
    handleCloseDialog();
  }}
  onCancel={handleCloseDialog}
  confirmButtonText="Déconnecter"
  cancelButtonText="Annuler"
  useThemeButtons={true} 
/>
    </Stack>
    </Box>
  );
}