import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  TextField,
  Paper,
  Alert,
  CircularProgress,
  List,
  ListItem,
  ListItemText,
  Divider,
  Chip
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import { useSessionStore } from '../store/sessionStore';

interface ConnectionHistory {
  id: string;
  url: string;
  timestamp: number;
  status: 'connected' | 'disconnected';
}

const WebSocketPage = () => {
  const navigate = useNavigate();
  const { 
    isSessionUnlocked, 
    currentKeypair, 
    isWebSocketConnected, 
    webSocketUrl,
    connectWebSocket,
    disconnectWebSocket
  } = useSessionStore();
  
  const [serverUrl, setServerUrl] = useState('');
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [connectionHistory, setConnectionHistory] = useState<ConnectionHistory[]>([]);

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

  // Load connection history from storage
  useEffect(() => {
    const loadConnectionHistory = async () => {
      try {
        const data = await chrome.storage.local.get('connectionHistory');
        if (data.connectionHistory) {
          setConnectionHistory(data.connectionHistory);
        }
      } catch (err) {
        console.error('Failed to load connection history:', err);
      }
    };

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

  const handleConnect = async () => {
    if (!serverUrl.trim() || !currentKeypair) return;
    
    setIsConnecting(true);
    setError(null);
    
    try {
      const success = await connectWebSocket(serverUrl);
      
      if (success) {
        // Add to connection history
        const newConnection: ConnectionHistory = {
          id: `conn-${Date.now()}`,
          url: serverUrl,
          timestamp: Date.now(),
          status: 'connected'
        };
        
        const updatedHistory = [newConnection, ...connectionHistory].slice(0, 10); // Keep last 10
        setConnectionHistory(updatedHistory);
        
        // Save to storage
        await chrome.storage.local.set({ connectionHistory: updatedHistory });
      } else {
        throw new Error('Failed to connect to WebSocket server');
      }
    } catch (err) {
      setError((err as Error).message || 'Failed to connect to WebSocket server');
    } finally {
      setIsConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    try {
      const success = await disconnectWebSocket();
      
      if (success && webSocketUrl) {
        // Update connection history
        const updatedHistory = connectionHistory.map(conn => 
          conn.url === webSocketUrl && conn.status === 'connected'
            ? { ...conn, status: 'disconnected' }
            : conn
        );
        
        setConnectionHistory(updatedHistory);
        
        // Save to storage
        await chrome.storage.local.set({ connectionHistory: updatedHistory });
      }
    } catch (err) {
      setError((err as Error).message || 'Failed to disconnect from WebSocket server');
    }
  };

  const handleQuickConnect = (url: string) => {
    setServerUrl(url);
    // Don't auto-connect to avoid unexpected connections
  };

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

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="h6" gutterBottom>
        WebSocket Connection
      </Typography>
      
      {!currentKeypair && (
        <Alert severity="warning" sx={{ mb: 2 }}>
          No keypair selected. Select a keypair before connecting to a WebSocket server.
        </Alert>
      )}
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      <Paper variant="outlined" sx={{ p: 2, mb: 2 }}>
        <Box sx={{ mb: 2 }}>
          <Typography variant="subtitle2" gutterBottom>
            Connection Status:
          </Typography>
          <Chip
            label={isWebSocketConnected ? 'Connected' : 'Disconnected'}
            color={isWebSocketConnected ? 'success' : 'default'}
            variant="outlined"
          />
          {isWebSocketConnected && webSocketUrl && (
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              Connected to: {webSocketUrl}
            </Typography>
          )}
        </Box>
        
        <Box sx={{ display: 'flex', gap: 1 }}>
          <TextField
            label="WebSocket Server URL"
            placeholder="wss://example.com/ws"
            value={serverUrl}
            onChange={(e) => setServerUrl(e.target.value)}
            fullWidth
            disabled={isConnecting || isWebSocketConnected || !currentKeypair}
          />
          
          {isWebSocketConnected ? (
            <Button
              variant="outlined"
              color="error"
              onClick={handleDisconnect}
            >
              Disconnect
            </Button>
          ) : (
            <Button
              variant="contained"
              color="primary"
              onClick={handleConnect}
              disabled={isConnecting || !serverUrl.trim() || !currentKeypair}
            >
              {isConnecting ? <CircularProgress size={24} /> : 'Connect'}
            </Button>
          )}
        </Box>
      </Paper>
      
      <Typography variant="subtitle1" gutterBottom>
        Connection History
      </Typography>
      
      {connectionHistory.length === 0 ? (
        <Paper sx={{ p: 3, textAlign: 'center' }}>
          <Typography variant="body1" color="text.secondary">
            No connection history yet.
          </Typography>
        </Paper>
      ) : (
        <Paper variant="outlined" sx={{ flexGrow: 1, overflow: 'auto' }}>
          <List disablePadding>
            {connectionHistory.map((conn, index) => (
              <Box key={conn.id}>
                {index > 0 && <Divider />}
                <ListItem 
                  button 
                  onClick={() => handleQuickConnect(conn.url)}
                  disabled={isWebSocketConnected}
                >
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Typography variant="subtitle2">
                          {conn.url}
                        </Typography>
                        <Chip
                          label={conn.status}
                          size="small"
                          color={conn.status === 'connected' ? 'success' : 'default'}
                          variant="outlined"
                        />
                      </Box>
                    }
                    secondary={
                      <Typography variant="body2" color="text.secondary">
                        {new Date(conn.timestamp).toLocaleString()}
                      </Typography>
                    }
                  />
                </ListItem>
              </Box>
            ))}
          </List>
        </Paper>
      )}
    </Box>
  );
};

export default WebSocketPage;
