import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  Alert,
  CircularProgress,
  List,
  ListItem,
  ListItemText,
  Divider,
  Card,
  CardContent,
  Grid
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import { useSessionStore } from '../store/sessionStore';
import LockIcon from '@mui/icons-material/Lock';
import SecurityIcon from '@mui/icons-material/Security';
// HistoryIcon removed as it's not used

interface SessionActivity {
  id: string;
  action: string;
  timestamp: number;
  details?: string;
}

const SessionPage = () => {
  const navigate = useNavigate();
  const { 
    isSessionUnlocked, 
    currentKeyspace, 
    currentKeypair,
    lockSession
  } = useSessionStore();
  
  const [sessionActivities, setSessionActivities] = useState<SessionActivity[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  // Redirect if not unlocked
  useEffect(() => {
    if (!isSessionUnlocked) {
      navigate('/');
    }
  }, [isSessionUnlocked, navigate]);

  // Load session activities from storage
  useEffect(() => {
    const loadSessionActivities = async () => {
      try {
        setIsLoading(true);
        const data = await chrome.storage.local.get('sessionActivities');
        if (data.sessionActivities) {
          setSessionActivities(data.sessionActivities);
        }
      } catch (err) {
        console.error('Failed to load session activities:', err);
      } finally {
        setIsLoading(false);
      }
    };

    if (isSessionUnlocked) {
      loadSessionActivities();
    }
  }, [isSessionUnlocked]);

  const handleLockSession = async () => {
    try {
      await lockSession();
      navigate('/');
    } catch (err) {
      console.error('Failed to lock session:', err);
    }
  };

  if (!isSessionUnlocked) {
    return null; // Will redirect via useEffect
  }

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="h6" gutterBottom>
        Session Management
      </Typography>
      
      <Grid container spacing={2} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={6}>
          <Card variant="outlined">
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                Current Keyspace
              </Typography>
              <Typography variant="h5" component="div">
                {currentKeyspace || 'None'}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={12} sm={6}>
          <Card variant="outlined">
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                Selected Keypair
              </Typography>
              <Typography variant="h5" component="div">
                {currentKeypair?.name || currentKeypair?.id || 'None'}
              </Typography>
              {currentKeypair && (
                <Typography variant="body2" color="text.secondary">
                  Type: {currentKeypair.type}
                </Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
      
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
        <Typography variant="subtitle1">
          Session Activity
        </Typography>
        
        <Button
          variant="outlined"
          color="error"
          startIcon={<LockIcon />}
          onClick={handleLockSession}
        >
          Lock Session
        </Button>
      </Box>
      
      {isLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      ) : sessionActivities.length === 0 ? (
        <Paper sx={{ p: 3, textAlign: 'center' }}>
          <Typography variant="body1" color="text.secondary">
            No session activity recorded yet.
          </Typography>
        </Paper>
      ) : (
        <Paper variant="outlined" sx={{ flexGrow: 1, overflow: 'auto' }}>
          <List disablePadding>
            {sessionActivities.map((activity, index) => (
              <Box key={activity.id}>
                {index > 0 && <Divider />}
                <ListItem>
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Typography variant="subtitle2">
                          {activity.action}
                        </Typography>
                      </Box>
                    }
                    secondary={
                      <>
                        <Typography variant="body2" color="text.secondary">
                          {new Date(activity.timestamp).toLocaleString()}
                        </Typography>
                        {activity.details && (
                          <Typography variant="body2" color="text.secondary">
                            {activity.details}
                          </Typography>
                        )}
                      </>
                    }
                  />
                </ListItem>
              </Box>
            ))}
          </List>
        </Paper>
      )}
      
      <Box sx={{ mt: 3 }}>
        <Alert severity="info" icon={<SecurityIcon />}>
          Your session is active. All cryptographic operations and script executions require explicit approval.
        </Alert>
      </Box>
    </Box>
  );
};

export default SessionPage;
