import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  CircularProgress,
  Tooltip
} from '@mui/material';
import {
  DevicesOther,
  Delete,
  Refresh,
  Computer,
  Smartphone,
  Tablet,
  Warning
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useSecurityNotification } from './SecurityNotificationProvider';
import axios from 'axios';
import { format } from 'date-fns';

const SessionManagement = () => {
  const { t } = useTranslation();
  const { token } = useAuthStore();
  const { notifySecuritySuccess, notifySecurityError, notifySecurityWarning } = useSecurityNotification();
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [terminateDialogOpen, setTerminateDialogOpen] = useState(false);
  const [terminateAllDialogOpen, setTerminateAllDialogOpen] = useState(false);
  const [sessionToTerminate, setSessionToTerminate] = useState(null);

  useEffect(() => {
    fetchSessions();
  }, []);

  const fetchSessions = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/sessions/my-sessions', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setSessions(response.data);
    } catch (error) {
      notifySecurityError(
        t('error'),
        error.response?.data?.error || 'Failed to fetch sessions'
      );
    } finally {
      setLoading(false);
    }
  };

  const getDeviceIcon = (userAgent) => {
    if (!userAgent) return <Computer />;
    
    const ua = userAgent.toLowerCase();
    if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
      return <Smartphone />;
    }
    if (ua.includes('tablet') || ua.includes('ipad')) {
      return <Tablet />;
    }
    return <Computer />;
  };

  const getDeviceName = (userAgent) => {
    if (!userAgent) return 'Unknown Device';
    
    const ua = userAgent.toLowerCase();
    if (ua.includes('chrome')) return 'Chrome Browser';
    if (ua.includes('firefox')) return 'Firefox Browser';
    if (ua.includes('safari') && !ua.includes('chrome')) return 'Safari Browser';
    if (ua.includes('edge')) return 'Edge Browser';
    if (ua.includes('mobile')) return 'Mobile Device';
    if (ua.includes('tablet')) return 'Tablet';
    return 'Desktop Browser';
  };

  const getLocation = (ipAddress) => {
    // In a real app, you might do IP geolocation
    return ipAddress || 'Unknown Location';
  };

  const handleTerminateSession = async () => {
    if (!sessionToTerminate) return;

    try {
      await axios.delete(`/api/sessions/${sessionToTerminate.id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      notifySecuritySuccess(t('security.terminateSession'));
      setTerminateDialogOpen(false);
      setSessionToTerminate(null);
      fetchSessions();
    } catch (error) {
      notifySecurityError(
        t('error'),
        error.response?.data?.error || 'Failed to terminate session'
      );
    }
  };

  const handleTerminateAllOthers = async () => {
    try {
      const response = await axios.post('/api/sessions/terminate-all-others', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });

      notifySecuritySuccess(
        `${response.data.count} ${t('security.terminateSession')}(s)`
      );
      setTerminateAllDialogOpen(false);
      fetchSessions();
    } catch (error) {
      notifySecurityError(
        t('error'),
        error.response?.data?.error || 'Failed to terminate sessions'
      );
    }
  };

  const openTerminateDialog = (session) => {
    setSessionToTerminate(session);
    setTerminateDialogOpen(true);
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  const otherSessions = sessions.filter(s => !s.isCurrent);

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <DevicesOther color="primary" fontSize="large" />
          <Typography variant="h5" fontWeight="bold">
            {t('security.activeSessions')}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            variant="outlined"
            startIcon={<Refresh />}
            onClick={fetchSessions}
            size="small"
          >
            {t('refresh')}
          </Button>
          {otherSessions.length > 0 && (
            <Button
              variant="outlined"
              color="error"
              onClick={() => setTerminateAllDialogOpen(true)}
              size="small"
            >
              {t('security.terminateAllSessions')}
            </Button>
          )}
        </Box>
      </Box>

      {sessions.length > 1 && (
        <Alert severity="info" sx={{ mb: 3 }}>
          {t('security.multipleDevices', { count: sessions.length })}
        </Alert>
      )}

      {sessions.length === 0 && (
        <Alert severity="warning">
          {t('security.noRecentActivity')}
        </Alert>
      )}

      {sessions.length > 0 && (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>{t('device')}</TableCell>
                <TableCell>{t('security.ipAddress')}</TableCell>
                <TableCell>{t('lastActive')}</TableCell>
                <TableCell>{t('created')}</TableCell>
                <TableCell>{t('security.status')}</TableCell>
                <TableCell align="right">{t('actions')}</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {sessions.map((session) => (
                <TableRow
                  key={session.id}
                  sx={{
                    backgroundColor: session.isCurrent ? 'action.selected' : 'inherit'
                  }}
                >
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      {getDeviceIcon(session.user_agent)}
                      <Box>
                        <Typography variant="body2" fontWeight={session.isCurrent ? 'bold' : 'normal'}>
                          {getDeviceName(session.user_agent)}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {session.user_agent?.substring(0, 50)}...
                        </Typography>
                      </Box>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {getLocation(session.ip_address)}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      {session.ip_address}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {session.last_activity 
                        ? format(new Date(session.last_activity), 'MMM d, yyyy HH:mm')
                        : 'N/A'
                      }
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {format(new Date(session.created_at), 'MMM d, yyyy HH:mm')}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    {session.isCurrent ? (
                      <Chip 
                        label={t('current')} 
                        color="primary" 
                        size="small"
                      />
                    ) : (
                      <Chip 
                        label={t('active')} 
                        color="success" 
                        size="small" 
                        variant="outlined"
                      />
                    )}
                  </TableCell>
                  <TableCell align="right">
                    {!session.isCurrent && (
                      <Tooltip title={t('security.terminateSession')}>
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => openTerminateDialog(session)}
                        >
                          <Delete />
                        </IconButton>
                      </Tooltip>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* Terminate Single Session Dialog */}
      <Dialog
        open={terminateDialogOpen}
        onClose={() => setTerminateDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Warning color="warning" />
            {t('security.terminateSession')}
          </Box>
        </DialogTitle>
        <DialogContent>
          <Typography gutterBottom>
            Are you sure you want to terminate this session?
          </Typography>
          {sessionToTerminate && (
            <Box sx={{ mt: 2, p: 2, bgcolor: 'action.hover', borderRadius: 1 }}>
              <Typography variant="body2">
                <strong>{t('device')}:</strong> {getDeviceName(sessionToTerminate.user_agent)}
              </Typography>
              <Typography variant="body2">
                <strong>{t('security.ipAddress')}:</strong> {sessionToTerminate.ip_address}
              </Typography>
              <Typography variant="body2">
                <strong>{t('lastActive')}:</strong> {format(new Date(sessionToTerminate.last_activity || sessionToTerminate.created_at), 'MMM d, yyyy HH:mm')}
              </Typography>
            </Box>
          )}
          <Alert severity="info" sx={{ mt: 2 }}>
            This device will be logged out immediately.
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setTerminateDialogOpen(false)}>
            {t('cancel')}
          </Button>
          <Button onClick={handleTerminateSession} color="error" variant="contained">
            {t('security.terminateSession')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Terminate All Other Sessions Dialog */}
      <Dialog
        open={terminateAllDialogOpen}
        onClose={() => setTerminateAllDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Warning color="error" />
            {t('security.terminateAllSessions')}
          </Box>
        </DialogTitle>
        <DialogContent>
          <Typography gutterBottom>
            Are you sure you want to terminate all other sessions?
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            This will log you out from all devices except this one. You'll need to log in again on those devices.
          </Alert>
          <Typography variant="body2" sx={{ mt: 2 }}>
            <strong>{otherSessions.length}</strong> session(s) will be terminated.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setTerminateAllDialogOpen(false)}>
            {t('cancel')}
          </Button>
          <Button onClick={handleTerminateAllOthers} color="error" variant="contained">
            {t('security.terminateAllSessions')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SessionManagement;
