import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Divider,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Paper,
  Alert,
  Chip
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import CheckIcon from '@mui/icons-material/Check';
import { useSessionStore } from '../store/sessionStore';
import { useNavigate } from 'react-router-dom';

const KeypairPage = () => {
  const navigate = useNavigate();
  const {
    isSessionUnlocked,
    availableKeypairs,
    currentKeypair,
    listKeypairs,
    selectKeypair,
    createKeypair
  } = useSessionStore();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [newKeypairName, setNewKeypairName] = useState('');
  const [newKeypairType, setNewKeypairType] = useState('Secp256k1');
  const [newKeypairDescription, setNewKeypairDescription] = useState('');
  const [isCreating, setIsCreating] = useState(false);

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

  // Load keypairs on mount
  useEffect(() => {
    const loadKeypairs = async () => {
      try {
        setIsLoading(true);
        await listKeypairs();
      } catch (err) {
        setError((err as Error).message || 'Failed to load keypairs');
      } finally {
        setIsLoading(false);
      }
    };

    if (isSessionUnlocked) {
      loadKeypairs();
    }
  }, [isSessionUnlocked, listKeypairs]);

  const handleSelectKeypair = async (keypairId: string) => {
    try {
      setIsLoading(true);
      await selectKeypair(keypairId);
    } catch (err) {
      setError((err as Error).message || 'Failed to select keypair');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateKeypair = async () => {
    try {
      setIsCreating(true);
      setError(null);
      
      await createKeypair(newKeypairType, {
        name: newKeypairName,
        description: newKeypairDescription
      });
      
      setCreateDialogOpen(false);
      setNewKeypairName('');
      setNewKeypairDescription('');
      
      // Refresh the list
      await listKeypairs();
    } catch (err) {
      setError((err as Error).message || 'Failed to create keypair');
    } finally {
      setIsCreating(false);
    }
  };

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

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">Keypair Management</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setCreateDialogOpen(true)}
          disabled={isLoading}
        >
          Create New
        </Button>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {isLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      ) : availableKeypairs.length === 0 ? (
        <Paper sx={{ p: 3, textAlign: 'center' }}>
          <Typography variant="body1" color="text.secondary">
            No keypairs found. Create your first keypair to get started.
          </Typography>
        </Paper>
      ) : (
        <Paper variant="outlined" sx={{ flexGrow: 1, overflow: 'auto' }}>
          <List disablePadding>
            {availableKeypairs.map((keypair: any, index: number) => (
              <Box key={keypair.id}>
                {index > 0 && <Divider />}
                <ListItem
                  button
                  selected={currentKeypair?.id === keypair.id}
                  onClick={() => handleSelectKeypair(keypair.id)}
                >
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        {keypair.name || keypair.id}
                        <Chip
                          label={keypair.type}
                          size="small"
                          color="primary"
                          variant="outlined"
                        />
                      </Box>
                    }
                    secondary={
                      <Typography variant="body2" color="text.secondary">
                        {keypair.description || 'No description'}
                        <br />
                        Created: {new Date(keypair.createdAt).toLocaleString()}
                      </Typography>
                    }
                  />
                  <ListItemSecondaryAction>
                    {currentKeypair?.id === keypair.id && (
                      <IconButton edge="end" disabled>
                        <CheckIcon color="success" />
                      </IconButton>
                    )}
                  </ListItemSecondaryAction>
                </ListItem>
              </Box>
            ))}
          </List>
        </Paper>
      )}

      {/* Create Keypair Dialog */}
      <Dialog open={createDialogOpen} onClose={() => setCreateDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Create New Keypair</DialogTitle>
        <DialogContent>
          <TextField
            label="Name"
            value={newKeypairName}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewKeypairName(e.target.value)}
            fullWidth
            margin="normal"
            disabled={isCreating}
          />

          <FormControl fullWidth margin="normal">
            <InputLabel>Type</InputLabel>
            <Select
              value={newKeypairType}
              onChange={(e) => setNewKeypairType(e.target.value)}
              disabled={isCreating}
            >
              <MenuItem value="Ed25519">Ed25519</MenuItem>
              <MenuItem value="Secp256k1">Secp256k1 (Ethereum)</MenuItem>
            </Select>
          </FormControl>

          <TextField
            label="Description"
            value={newKeypairDescription}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewKeypairDescription(e.target.value)}
            fullWidth
            margin="normal"
            multiline
            rows={2}
            disabled={isCreating}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCreateDialogOpen(false)} disabled={isCreating}>
            Cancel
          </Button>
          <Button
            onClick={handleCreateKeypair}
            color="primary"
            variant="contained"
            disabled={isCreating || !newKeypairName}
          >
            {isCreating ? <CircularProgress size={24} /> : 'Create'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default KeypairPage;
