/**
 * Cryptographic Operations Page
 * 
 * This page provides a UI for:
 * - Encrypting/decrypting data using the keyspace's symmetric cipher
 * - Signing/verifying messages using the selected keypair
 */

import { useState, useEffect } from 'react';
import type { SyntheticEvent } from '../types';
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Tabs,
  Tab,
  CircularProgress,
  Alert,
  Divider,
  IconButton,
  Tooltip,
} from '@mui/material';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { useSessionStore } from '../store/sessionStore';
import { useCryptoStore } from '../store/cryptoStore';
import { useNavigate } from 'react-router-dom';

const CryptoPage = () => {
  const navigate = useNavigate();
  const { isSessionUnlocked, currentKeypair } = useSessionStore();
  const {
    encryptData,
    decryptData,
    signMessage,
    verifySignature,
    isEncrypting,
    isDecrypting,
    isSigning,
    isVerifying,
    error,
    clearError
  } = useCryptoStore();
  
  const [activeTab, setActiveTab] = useState(0);
  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  
  // Encryption state
  const [plaintext, setPlaintext] = useState('');
  const [encryptedData, setEncryptedData] = useState('');
  
  // Decryption state
  const [ciphertext, setCiphertext] = useState('');
  const [decryptedData, setDecryptedData] = useState('');
  
  // Signing state
  const [messageToSign, setMessageToSign] = useState('');
  const [signature, setSignature] = useState('');
  
  // Verification state
  const [messageToVerify, setMessageToVerify] = useState('');
  const [signatureToVerify, setSignatureToVerify] = useState('');
  const [isVerified, setIsVerified] = useState<boolean | null>(null);
  
  // Redirect if not unlocked
  useEffect(() => {
    if (!isSessionUnlocked) {
      navigate('/');
    }
  }, [isSessionUnlocked, navigate]);
  
  const handleTabChange = (_event: React.SyntheticEvent<Element, Event>, newValue: number) => {
    setActiveTab(newValue);
    clearError();
    setCopySuccess(null);
  };
  
  const handleEncrypt = async () => {
    try {
      const result = await encryptData(plaintext);
      setEncryptedData(result);
    } catch (err) {
      // Error is already handled in the store
    }
  };
  
  const handleDecrypt = async () => {
    try {
      const result = await decryptData(ciphertext);
      setDecryptedData(result);
    } catch (err) {
      // Error is already handled in the store
    }
  };
  
  const handleSign = async () => {
    try {
      const result = await signMessage(messageToSign);
      setSignature(result);
    } catch (err) {
      // Error is already handled in the store
    }
  };
  
  const handleVerify = async () => {
    try {
      const result = await verifySignature(messageToVerify, signatureToVerify);
      setIsVerified(result);
    } catch (err) {
      setIsVerified(false);
      // Error is already handled in the store
    }
  };
  
  const copyToClipboard = (text: string, label: string) => {
    navigator.clipboard.writeText(text).then(
      () => {
        setCopySuccess(`${label} copied to clipboard!`);
        setTimeout(() => setCopySuccess(null), 2000);
      },
      () => {
        setCopySuccess('Failed to copy!');
      }
    );
  };
  
  if (!isSessionUnlocked) {
    return null; // Will redirect via useEffect
  }
  
  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="h6" sx={{ mb: 2 }}>Cryptographic Operations</Typography>
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      {copySuccess && (
        <Alert severity="success" sx={{ mb: 2 }}>
          {copySuccess}
        </Alert>
      )}
      
      <Paper sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Tabs with smaller width and scrollable */}
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs 
            value={activeTab} 
            onChange={handleTabChange}
            variant="scrollable"
            scrollButtons="auto"
            allowScrollButtonsMobile
            sx={{ minHeight: '48px' }}
          >
            <Tab label="Encrypt" sx={{ minWidth: '80px', minHeight: '48px', py: 0 }} />
            <Tab label="Decrypt" sx={{ minWidth: '80px', minHeight: '48px', py: 0 }} />
            <Tab label="Sign" sx={{ minWidth: '80px', minHeight: '48px', py: 0 }} />
            <Tab label="Verify" sx={{ minWidth: '80px', minHeight: '48px', py: 0 }} />
          </Tabs>
        </Box>
        
        {/* Content area with proper scrolling */}
        <Box sx={{ p: 2, flexGrow: 1, overflow: 'auto', height: 'calc(100% - 48px)' }}>
          {/* Encryption Tab */}
          {activeTab === 0 && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>Encrypt Data</Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                Data will be encrypted using ChaCha20-Poly1305 with a key derived from your keyspace password.
              </Typography>
              
              <TextField
                label="Data to Encrypt"
                multiline
                rows={4}
                fullWidth
                value={plaintext}
                onChange={(e) => setPlaintext(e.target.value)}
                margin="normal"
              />
              
              <Button
                variant="contained"
                onClick={handleEncrypt}
                disabled={!plaintext || isEncrypting}
                sx={{ mt: 2 }}
              >
                {isEncrypting ? <CircularProgress size={24} /> : 'Encrypt'}
              </Button>
              
              {encryptedData && (
                <Box sx={{ mt: 3 }}>
                  <Divider sx={{ my: 2 }} />
                  <Typography variant="subtitle1">Encrypted Result</Typography>
                  <Box sx={{ position: 'relative' }}>
                    <TextField
                      label="Encrypted Data (Base64)"
                      multiline
                      rows={4}
                      fullWidth
                      value={encryptedData}
                      InputProps={{ readOnly: true }}
                      margin="normal"
                    />
                    <Tooltip title="Copy to clipboard">
                      <IconButton 
                        sx={{ position: 'absolute', top: 8, right: 8 }}
                        onClick={() => copyToClipboard(encryptedData, 'Encrypted data')}
                      >
                        <ContentCopyIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  </Box>
                </Box>
              )}
            </Box>
          )}
          
          {/* Decryption Tab */}
          {activeTab === 1 && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>Decrypt Data</Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                Paste encrypted data (in Base64 format) to decrypt it using your keyspace password.
              </Typography>
              
              <TextField
                label="Encrypted Data (Base64)"
                multiline
                rows={4}
                fullWidth
                value={ciphertext}
                onChange={(e) => setCiphertext(e.target.value)}
                margin="normal"
              />
              
              <Button
                variant="contained"
                onClick={handleDecrypt}
                disabled={!ciphertext || isDecrypting}
                sx={{ mt: 2 }}
              >
                {isDecrypting ? <CircularProgress size={24} /> : 'Decrypt'}
              </Button>
              
              {decryptedData && (
                <Box sx={{ mt: 3 }}>
                  <Divider sx={{ my: 2 }} />
                  <Typography variant="subtitle1">Decrypted Result</Typography>
                  <Box sx={{ position: 'relative' }}>
                    <TextField
                      label="Decrypted Data"
                      multiline
                      rows={4}
                      fullWidth
                      value={decryptedData}
                      InputProps={{ readOnly: true }}
                      margin="normal"
                    />
                    <Tooltip title="Copy to clipboard">
                      <IconButton 
                        sx={{ position: 'absolute', top: 8, right: 8 }}
                        onClick={() => copyToClipboard(decryptedData, 'Decrypted data')}
                      >
                        <ContentCopyIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  </Box>
                </Box>
              )}
            </Box>
          )}
          
          {/* Signing Tab */}
          {activeTab === 2 && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>Sign Message</Typography>
              
              {!currentKeypair ? (
                <Alert severity="warning" sx={{ mb: 2 }}>
                  Please select a keypair from the Keypair page before signing messages.
                </Alert>
              ) : (
                <Alert severity="info" sx={{ mb: 2 }}>
                  Signing with keypair: {currentKeypair.name || currentKeypair.id.substring(0, 8)}...
                </Alert>
              )}
              
              <TextField
                label="Message to Sign"
                multiline
                rows={4}
                fullWidth
                value={messageToSign}
                onChange={(e) => setMessageToSign(e.target.value)}
                margin="normal"
                disabled={!currentKeypair}
              />
              <Button
                variant="contained"
                onClick={handleSign}
                disabled={!messageToSign || !currentKeypair || isSigning}
                sx={{ mt: 2 }}
              >
                {isSigning ? <CircularProgress size={24} /> : 'Sign Message'}
              </Button>
              
              {signature && (
                <Box sx={{ mt: 3 }}>
                  <Divider sx={{ my: 2 }} />
                  <Typography variant="subtitle1">Signature</Typography>
                  <Box sx={{ position: 'relative' }}>
                    <TextField
                      label="Signature (Hex)"
                      multiline
                      rows={4}
                      fullWidth
                      value={signature}
                      InputProps={{ readOnly: true }}
                      margin="normal"
                    />
                    <Tooltip title="Copy to clipboard">
                      <IconButton 
                        sx={{ position: 'absolute', top: 8, right: 8 }}
                        onClick={() => copyToClipboard(signature, 'Signature')}
                      >
                        <ContentCopyIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  </Box>
                </Box>
              )}
            </Box>
          )}
          
          {/* Verification Tab */}
          {activeTab === 3 && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>Verify Signature</Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                Verify that a message was signed by the currently selected keypair.
              </Typography>
              
              <TextField
                label="Message"
                multiline
                rows={4}
                fullWidth
                value={messageToVerify}
                onChange={(e) => setMessageToVerify(e.target.value)}
                margin="normal"
              />
              <TextField
                label="Signature (Hex)"
                multiline
                rows={2}
                fullWidth
                value={signatureToVerify}
                onChange={(e) => setSignatureToVerify(e.target.value)}
                margin="normal"
              />
              <Button
                variant="contained"
                onClick={handleVerify}
                disabled={!messageToVerify || !signatureToVerify || isVerifying}
                sx={{ mt: 2 }}
              >
                {isVerifying ? <CircularProgress size={24} /> : 'Verify Signature'}
              </Button>
              
              {isVerified !== null && (
                <Box sx={{ mt: 3 }}>
                  <Alert severity={isVerified ? "success" : "error"}>
                    {isVerified 
                      ? "Signature is valid! The message was signed by the expected keypair." 
                      : "Invalid signature. The message may have been tampered with or signed by a different keypair."}
                  </Alert>
                </Box>
              )}
            </Box>
          )}
        </Box>
      </Paper>
    </Box>
  );
};

export default CryptoPage;
