import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Grid,
  Alert,
  CircularProgress,
  LinearProgress,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Divider,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow
} from '@mui/material';
import {
  Lock,
  LockOpen,
  Security,
  Warning,
  CheckCircle,
  Info,
  VpnKey,
  Settings as SettingsIcon,
  Shield,
  Scanner,
  Refresh,
  VerifiedUser,
  ArrowBack
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';
import { useErrorNotification } from './ErrorNotificationProvider';
import { useNavigate } from 'react-router-dom';

function EncryptionManagementDashboard() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const token = useAuthStore((state) => state.token);
  const { showError, showSuccess, showWarning } = useErrorNotification();

  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState(null);
  const [scanResults, setScanResults] = useState(null);
  const [verifyResults, setVerifyResults] = useState(null);
  const [migrating, setMigrating] = useState(false);
  const [scanning, setScanning] = useState(false);
  const [verifying, setVerifying] = useState(false);
  
  // Dialogs
  const [scanDialogOpen, setScanDialogOpen] = useState(false);
  const [migrateDialogOpen, setMigrateDialogOpen] = useState(false);
  const [verifyDialogOpen, setVerifyDialogOpen] = useState(false);

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

  const fetchEncryptionStatus = async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/encryption/status', {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setStatus(response.data.data);
      }
    } catch (error) {
      showError(t('encryption.fetchError'));
      console.error('Error fetching encryption status:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleScan = async () => {
    try {
      setScanning(true);
      const response = await axios.get('/api/encryption/scan', {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setScanResults(response.data.data);
        setScanDialogOpen(true);
        
        if (response.data.data.totalIssues === 0) {
          showSuccess(t('encryption.scanComplete'));
        } else {
          showWarning(t('encryption.issuesFound', { count: response.data.data.totalIssues }));
        }
      }
    } catch (error) {
      showError(t('encryption.scanError'));
      console.error('Error scanning:', error);
    } finally {
      setScanning(false);
    }
  };

  const handleMigrate = async () => {
    try {
      setMigrating(true);
      const response = await axios.post('/api/encryption/migrate', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        showSuccess(t('encryption.migrationComplete', { count: response.data.data.totalMigrated }));
        setMigrateDialogOpen(false);
        
        // Refresh status
        await fetchEncryptionStatus();
        
        // Re-scan to show updated results
        await handleScan();
      }
    } catch (error) {
      showError(t('encryption.migrationError'));
      console.error('Error migrating:', error);
    } finally {
      setMigrating(false);
    }
  };

  const handleVerify = async () => {
    try {
      setVerifying(true);
      const response = await axios.post('/api/encryption/verify', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setVerifyResults(response.data.data);
        setVerifyDialogOpen(true);
        showSuccess(t('encryption.verifyComplete'));
      }
    } catch (error) {
      showError(t('encryption.verifyError'));
      console.error('Error verifying:', error);
    } finally {
      setVerifying(false);
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  if (!status) {
    return (
      <Alert severity="error">
        {t('encryption.statusError')}
      </Alert>
    );
  }

  const getStatusColor = (status) => {
    if (status === 'secure') return 'success';
    if (status === 'default-key') return 'warning';
    return 'error';
  };

  const getEncryptionPercentage = (stats) => {
    if (!stats) return 0;
    const total = Object.values(stats).reduce((sum, s) => sum + (s.total || 0), 0);
    const encrypted = Object.values(stats).reduce((sum, s) => sum + (s.encrypted || 0), 0);
    return total > 0 ? Math.round((encrypted / total) * 100) : 100;
  };

  const encryptionPercentage = getEncryptionPercentage(status.statistics);

  return (
    <Box>
      {/* Header with Back Button */}
      <Box mb={3}>
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
          <Box display="flex" alignItems="center" gap={1}>
            <Button
              startIcon={<ArrowBack />}
              onClick={() => navigate('/security')}
              variant="text"
              color="primary"
            >
              {t('common.back')}
            </Button>
            <Typography variant="h5" sx={{ ml: 1 }}>
              <Shield sx={{ mr: 1, verticalAlign: 'middle' }} />
              {t('encryption.title')}
            </Typography>
          </Box>
          <Button
            variant="outlined"
            startIcon={<Refresh />}
            onClick={fetchEncryptionStatus}
          >
            {t('common.refresh')}
          </Button>
        </Box>
        <Typography variant="body2" color="textSecondary" sx={{ ml: 10 }}>
          {t('encryption.subtitle')}
        </Typography>
      </Box>

      {/* Warning if default key is being used */}
      {status.status === 'default-key' && (
        <Alert severity="warning" sx={{ mb: 3 }} icon={<Warning />}>
          <Typography variant="subtitle2" gutterBottom>
            {status.warning}
          </Typography>
          <Typography variant="body2">
            {t('encryption.recommendations')}:
          </Typography>
          <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
            {status.recommendations.map((rec, idx) => (
              <li key={idx}><Typography variant="body2">{rec}</Typography></li>
            ))}
          </ul>
        </Alert>
      )}

      {/* Status Cards */}
      <Grid container spacing={3} mb={3}>
        {/* Encryption Status */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <Lock sx={{ mr: 1, color: 'primary.main' }} />
                <Typography variant="h6">
                  {t('encryption.status')}
                </Typography>
              </Box>
              
              <Chip
                label={status.status === 'secure' ? t('encryption.secure') : t('encryption.defaultKey')}
                color={getStatusColor(status.status)}
                icon={status.status === 'secure' ? <CheckCircle /> : <Warning />}
                sx={{ mb: 2 }}
              />

              <Typography variant="body2" color="textSecondary" gutterBottom>
                {t('encryption.algorithm')}: <strong>{status.algorithm}</strong>
              </Typography>
              <Typography variant="body2" color="textSecondary">
                {t('encryption.keySize')}: <strong>{status.keySize} bits</strong>
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* Encryption Coverage */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" mb={2}>
                <VerifiedUser sx={{ mr: 1, color: 'success.main' }} />
                <Typography variant="h6">
                  {t('encryption.coverage')}
                </Typography>
              </Box>
              
              <Box display="flex" alignItems="center" mb={1}>
                <Typography variant="h3" color="primary">
                  {encryptionPercentage}%
                </Typography>
                <Typography variant="body2" color="textSecondary" ml={1}>
                  {t('encryption.encrypted')}
                </Typography>
              </Box>

              <LinearProgress
                variant="determinate"
                value={encryptionPercentage}
                sx={{ height: 8, borderRadius: 4, mb: 2 }}
                color={encryptionPercentage === 100 ? 'success' : 'warning'}
              />

              <Typography variant="body2" color="textSecondary">
                {status.statistics && (
                  <>
                    {Object.entries(status.statistics).map(([key, value]) => (
                      <div key={key}>
                        {t(`encryption.${key}`)}: {value.encrypted}/{value.total}
                      </div>
                    ))}
                  </>
                )}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Statistics Table */}
      {status.statistics && (
        <Card sx={{ mb: 3 }}>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              <VpnKey sx={{ mr: 1, verticalAlign: 'middle' }} />
              {t('encryption.dataTypes')}
            </Typography>

            <TableContainer component={Paper} variant="outlined">
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>{t('encryption.dataType')}</TableCell>
                    <TableCell align="right">{t('encryption.total')}</TableCell>
                    <TableCell align="right">{t('encryption.encrypted')}</TableCell>
                    <TableCell align="right">{t('encryption.percentage')}</TableCell>
                    <TableCell align="center">{t('encryption.status')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {Object.entries(status.statistics).map(([key, value]) => {
                    const percentage = value.total > 0 
                      ? Math.round((value.encrypted / value.total) * 100)
                      : 100;
                    
                    return (
                      <TableRow key={key}>
                        <TableCell>
                          {t(`encryption.${key}`)}
                        </TableCell>
                        <TableCell align="right">{value.total}</TableCell>
                        <TableCell align="right">{value.encrypted}</TableCell>
                        <TableCell align="right">{percentage}%</TableCell>
                        <TableCell align="center">
                          {percentage === 100 ? (
                            <CheckCircle color="success" />
                          ) : (
                            <Warning color="warning" />
                          )}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
          </CardContent>
        </Card>
      )}

      {/* Action Buttons */}
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            <SettingsIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
            {t('encryption.actions')}
          </Typography>

          <Grid container spacing={2}>
            <Grid item xs={12} sm={4}>
              <Button
                variant="contained"
                fullWidth
                startIcon={scanning ? <CircularProgress size={20} /> : <Scanner />}
                onClick={handleScan}
                disabled={scanning}
              >
                {t('encryption.scanButton')}
              </Button>
            </Grid>

            <Grid item xs={12} sm={4}>
              <Button
                variant="contained"
                fullWidth
                color="warning"
                startIcon={migrating ? <CircularProgress size={20} /> : <Lock />}
                onClick={() => setMigrateDialogOpen(true)}
                disabled={migrating || encryptionPercentage === 100}
              >
                {t('encryption.migrateButton')}
              </Button>
            </Grid>

            <Grid item xs={12} sm={4}>
              <Button
                variant="outlined"
                fullWidth
                startIcon={verifying ? <CircularProgress size={20} /> : <VerifiedUser />}
                onClick={handleVerify}
                disabled={verifying}
              >
                {t('encryption.verifyButton')}
              </Button>
            </Grid>
          </Grid>

          <Typography variant="body2" color="textSecondary" mt={2}>
            <Info sx={{ fontSize: 16, verticalAlign: 'middle', mr: 0.5 }} />
            {t('encryption.actionsHelp')}
          </Typography>
        </CardContent>
      </Card>

      {/* Scan Results Dialog */}
      <Dialog
        open={scanDialogOpen}
        onClose={() => setScanDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          <Scanner sx={{ mr: 1, verticalAlign: 'middle' }} />
          {t('encryption.scanResults')}
        </DialogTitle>
        <DialogContent>
          {scanResults && (
            <>
              {scanResults.findings.length === 0 ? (
                <Alert severity="success" icon={<CheckCircle />}>
                  {t('encryption.noIssuesFound')}
                </Alert>
              ) : (
                <>
                  <Alert severity="warning" sx={{ mb: 2 }}>
                    {t('encryption.foundIssues', { count: scanResults.totalIssues })}
                  </Alert>

                  <List>
                    {scanResults.findings.map((finding, idx) => (
                      <React.Fragment key={idx}>
                        <ListItem>
                          <ListItemIcon>
                            <Warning color={finding.severity === 'high' ? 'error' : 'warning'} />
                          </ListItemIcon>
                          <ListItemText
                            primary={`${finding.table}.${finding.field}`}
                            secondary={
                              <>
                                <Typography component="span" variant="body2">
                                  {finding.description}
                                </Typography>
                                <br />
                                <Typography component="span" variant="caption" color="error">
                                  {t('encryption.unencryptedCount')}: {finding.count}
                                </Typography>
                              </>
                            }
                          />
                          <Chip
                            label={finding.severity}
                            color={finding.severity === 'high' ? 'error' : 'warning'}
                            size="small"
                          />
                        </ListItem>
                        {idx < scanResults.findings.length - 1 && <Divider />}
                      </React.Fragment>
                    ))}
                  </List>

                  <Typography variant="body2" color="textSecondary" mt={2}>
                    <strong>{t('encryption.recommendation')}:</strong> {scanResults.recommendation}
                  </Typography>
                </>
              )}
            </>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setScanDialogOpen(false)}>
            {t('common.close')}
          </Button>
          {scanResults && scanResults.findings.length > 0 && (
            <Button
              variant="contained"
              color="warning"
              onClick={() => {
                setScanDialogOpen(false);
                setMigrateDialogOpen(true);
              }}
            >
              {t('encryption.migrateNow')}
            </Button>
          )}
        </DialogActions>
      </Dialog>

      {/* Migrate Confirmation Dialog */}
      <Dialog
        open={migrateDialogOpen}
        onClose={() => !migrating && setMigrateDialogOpen(false)}
      >
        <DialogTitle>
          <Lock sx={{ mr: 1, verticalAlign: 'middle' }} />
          {t('encryption.confirmMigration')}
        </DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            {t('encryption.migrationWarning')}
          </Alert>

          <Typography variant="body2" gutterBottom>
            {t('encryption.migrationDescription')}
          </Typography>

          <ul style={{ marginTop: '8px' }}>
            <li><Typography variant="body2">{t('encryption.migrationStep1')}</Typography></li>
            <li><Typography variant="body2">{t('encryption.migrationStep2')}</Typography></li>
            <li><Typography variant="body2">{t('encryption.migrationStep3')}</Typography></li>
          </ul>

          {migrating && (
            <Box mt={2}>
              <LinearProgress />
              <Typography variant="body2" color="textSecondary" align="center" mt={1}>
                {t('encryption.migrating')}
              </Typography>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setMigrateDialogOpen(false)} disabled={migrating}>
            {t('common.cancel')}
          </Button>
          <Button
            variant="contained"
            color="warning"
            onClick={handleMigrate}
            disabled={migrating}
          >
            {migrating ? t('encryption.migrating') : t('encryption.startMigration')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Verify Results Dialog */}
      <Dialog
        open={verifyDialogOpen}
        onClose={() => setVerifyDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          <VerifiedUser sx={{ mr: 1, verticalAlign: 'middle' }} />
          {t('encryption.verificationResults')}
        </DialogTitle>
        <DialogContent>
          {verifyResults && (
            <>
              {Object.entries(verifyResults).map(([key, value]) => (
                <Box key={key} mb={2}>
                  <Typography variant="subtitle2" gutterBottom>
                    {t(`encryption.${key}`)}
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={4}>
                      <Typography variant="body2" color="textSecondary">
                        {t('encryption.tested')}: {value.tested}
                      </Typography>
                    </Grid>
                    <Grid item xs={4}>
                      <Typography variant="body2" color="success.main">
                        {t('encryption.valid')}: {value.valid}
                      </Typography>
                    </Grid>
                    <Grid item xs={4}>
                      <Typography variant="body2" color="error.main">
                        {t('encryption.invalid')}: {value.invalid}
                      </Typography>
                    </Grid>
                  </Grid>
                  {value.invalid > 0 && (
                    <Alert severity="error" sx={{ mt: 1 }}>
                      {t('encryption.invalidDataFound')}
                    </Alert>
                  )}
                  {value.tested > 0 && value.invalid === 0 && (
                    <Alert severity="success" sx={{ mt: 1 }}>
                      {t('encryption.allDataValid')}
                    </Alert>
                  )}
                </Box>
              ))}
            </>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setVerifyDialogOpen(false)}>
            {t('common.close')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default EncryptionManagementDashboard;
