import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Grid,
  Card,
  CardContent,
  Chip,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Alert,
  CircularProgress,
  Tabs,
  Tab,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  IconButton,
  Tooltip
} from '@mui/material';
import {
  Security,
  BugReport,
  Refresh,
  Delete,
  Visibility,
  Warning,
  CheckCircle,
  Error as ErrorIcon,
  Policy,
  Shield,
  Lock,
  VpnLock,
  ArrowBack
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { useSecurityNotification } from './SecurityNotificationProvider';
import axios from 'axios';
import { format } from 'date-fns';

const CSPDashboard = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { token, user } = useAuthStore();
  const { notifySecuritySuccess, notifySecurityError } = useSecurityNotification();
  const [loading, setLoading] = useState(true);
  const [tabValue, setTabValue] = useState(0);
  
  // CSP State
  const [cspStats, setCspStats] = useState(null);
  const [cspViolations, setCspViolations] = useState([]);
  const [cspPolicy, setCspPolicy] = useState(null);
  const [violationDialogOpen, setViolationDialogOpen] = useState(false);
  const [selectedViolation, setSelectedViolation] = useState(null);
  const [clearDays, setClearDays] = useState(30);

  useEffect(() => {
    if (user?.role === 'admin') {
      fetchCSPData();
    }
  }, [user]);

  const fetchCSPData = async () => {
    setLoading(true);
    try {
      const [statsRes, violationsRes, policyRes] = await Promise.all([
        axios.get('/api/csp/stats?days=7', {
          headers: { Authorization: `Bearer ${token}` }
        }),
        axios.get('/api/csp/violations?limit=50', {
          headers: { Authorization: `Bearer ${token}` }
        }),
        axios.get('/api/csp/policy', {
          headers: { Authorization: `Bearer ${token}` }
        })
      ]);

      setCspStats(statsRes.data);
      setCspViolations(violationsRes.data.violations);
      setCspPolicy(policyRes.data);
    } catch (error) {
      notifySecurityError(
        t('error'),
        error.response?.data?.error || 'Failed to fetch CSP data'
      );
    } finally {
      setLoading(false);
    }
  };

  const handleClearViolations = async () => {
    try {
      const response = await axios.delete(`/api/csp/violations?days=${clearDays}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      notifySecuritySuccess(
        `${response.data.deleted} ${t('security.cspViolationsCleared')}`
      );
      fetchCSPData();
    } catch (error) {
      notifySecurityError(
        t('error'),
        error.response?.data?.error || 'Failed to clear violations'
      );
    }
  };

  const handleViewViolation = (violation) => {
    setSelectedViolation(violation);
    setViolationDialogOpen(true);
  };

  if (user?.role !== 'admin') {
    return (
      <Container maxWidth="md">
        <Alert severity="warning" sx={{ mt: 4 }}>
          {t('security.adminAccessRequired')}
        </Alert>
      </Container>
    );
  }

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Container maxWidth="xl">
      <Box sx={{ py: 3 }}>
        {/* Header */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Security fontSize="large" color="primary" />
            <Typography variant="h4" fontWeight="bold">
              {t('security.cspDashboard')}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              variant="outlined"
              startIcon={<ArrowBack />}
              onClick={() => navigate('/security')}
            >
              {t('backToSecurity')}
            </Button>
            <Button
              variant="outlined"
              startIcon={<Refresh />}
              onClick={fetchCSPData}
            >
              {t('refresh')}
            </Button>
          </Box>
        </Box>

        {/* CSP Policy Status */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
            <Shield color="primary" />
            <Typography variant="h6" fontWeight="bold">
              {t('security.cspPolicyStatus')}
            </Typography>
          </Box>
          <Grid container spacing={2}>
            <Grid item xs={12} md={4}>
              <Card>
                <CardContent>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                    <Policy color="primary" />
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.mode')}
                    </Typography>
                  </Box>
                  <Chip
                    label={cspPolicy?.mode === 'enforce' ? t('security.enforcing') : t('security.reportOnly')}
                    color={cspPolicy?.mode === 'enforce' ? 'success' : 'warning'}
                    size="small"
                  />
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} md={4}>
              <Card>
                <CardContent>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                    <BugReport color="error" />
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.totalViolations')} (7 {t('days')})
                    </Typography>
                  </Box>
                  <Typography variant="h4" fontWeight="bold">
                    {cspStats?.total || 0}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} md={4}>
              <Card>
                <CardContent>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                    <Lock color="success" />
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.policyDirectives')}
                    </Typography>
                  </Box>
                  <Typography variant="h4" fontWeight="bold">
                    {cspPolicy ? Object.keys(cspPolicy.policy).length : 0}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </Paper>

        {/* Tabs */}
        <Paper sx={{ mb: 3 }}>
          <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)}>
            <Tab label={t('security.violations')} icon={<Warning />} iconPosition="start" />
            <Tab label={t('security.statistics')} icon={<BugReport />} iconPosition="start" />
            <Tab label={t('security.policy')} icon={<Policy />} iconPosition="start" />
          </Tabs>
        </Paper>

        {/* Tab Content */}
        {tabValue === 0 && (
          <Paper sx={{ p: 3 }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
              <Typography variant="h6" fontWeight="bold">
                {t('security.recentViolations')}
              </Typography>
              <Box sx={{ display: 'flex', gap: 1 }}>
                <FormControl size="small" sx={{ minWidth: 120 }}>
                  <InputLabel>{t('security.clearOlderThan')}</InputLabel>
                  <Select
                    value={clearDays}
                    onChange={(e) => setClearDays(e.target.value)}
                    label={t('security.clearOlderThan')}
                  >
                    <MenuItem value={7}>7 {t('days')}</MenuItem>
                    <MenuItem value={14}>14 {t('days')}</MenuItem>
                    <MenuItem value={30}>30 {t('days')}</MenuItem>
                    <MenuItem value={90}>90 {t('days')}</MenuItem>
                  </Select>
                </FormControl>
                <Button
                  variant="outlined"
                  color="error"
                  startIcon={<Delete />}
                  onClick={handleClearViolations}
                >
                  {t('clear')}
                </Button>
              </Box>
            </Box>

            {cspViolations.length === 0 ? (
              <Alert severity="success" icon={<CheckCircle />}>
                {t('security.noViolations')}
              </Alert>
            ) : (
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>{t('security.timestamp')}</TableCell>
                      <TableCell>{t('security.violatedDirective')}</TableCell>
                      <TableCell>{t('security.blockedUri')}</TableCell>
                      <TableCell>{t('security.sourceFile')}</TableCell>
                      <TableCell>{t('security.ipAddress')}</TableCell>
                      <TableCell align="right">{t('actions')}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {cspViolations.map((violation) => (
                      <TableRow key={violation.id}>
                        <TableCell>
                          {format(new Date(violation.created_at), 'MMM d, HH:mm:ss')}
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={violation.violated_directive}
                            size="small"
                            color="error"
                            variant="outlined"
                          />
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption" noWrap sx={{ maxWidth: 200, display: 'block' }}>
                            {violation.blocked_uri || 'N/A'}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption" noWrap sx={{ maxWidth: 200, display: 'block' }}>
                            {violation.source_file || 'N/A'}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="caption">
                            {violation.ip_address}
                          </Typography>
                        </TableCell>
                        <TableCell align="right">
                          <Tooltip title={t('security.viewDetails')}>
                            <IconButton
                              size="small"
                              onClick={() => handleViewViolation(violation)}
                            >
                              <Visibility />
                            </IconButton>
                          </Tooltip>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Paper>
        )}

        {tabValue === 1 && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" fontWeight="bold" gutterBottom>
              {t('security.violationStatistics')}
            </Typography>
            <Grid container spacing={3}>
              {/* By Directive */}
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
                  {t('security.byDirective')}
                </Typography>
                {cspStats?.byDirective?.length > 0 ? (
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>{t('security.directive')}</TableCell>
                          <TableCell align="right">{t('count')}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {cspStats.byDirective.map((item, idx) => (
                          <TableRow key={idx}>
                            <TableCell>
                              <Chip label={item.violated_directive} size="small" color="error" variant="outlined" />
                            </TableCell>
                            <TableCell align="right">
                              <Typography variant="h6">{item.count}</Typography>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                ) : (
                  <Alert severity="info">{t('security.noData')}</Alert>
                )}
              </Grid>

              {/* By URI */}
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle1" fontWeight="bold" gutterBottom>
                  {t('security.byBlockedUri')}
                </Typography>
                {cspStats?.byUri?.length > 0 ? (
                  <TableContainer>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>{t('security.blockedUri')}</TableCell>
                          <TableCell align="right">{t('count')}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {cspStats.byUri.map((item, idx) => (
                          <TableRow key={idx}>
                            <TableCell>
                              <Typography variant="caption" noWrap sx={{ maxWidth: 300, display: 'block' }}>
                                {item.blocked_uri || 'inline'}
                              </Typography>
                            </TableCell>
                            <TableCell align="right">
                              <Typography variant="h6">{item.count}</Typography>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                ) : (
                  <Alert severity="info">{t('security.noData')}</Alert>
                )}
              </Grid>
            </Grid>
          </Paper>
        )}

        {tabValue === 2 && cspPolicy && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" fontWeight="bold" gutterBottom>
              {t('security.currentCspPolicy')}
            </Typography>
            <Alert severity="info" sx={{ mb: 2 }}>
              {cspPolicy.mode === 'enforce' 
                ? t('security.cspEnforcedDescription')
                : t('security.cspReportOnlyDescription')}
            </Alert>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>{t('security.directive')}</TableCell>
                    <TableCell>{t('security.allowedSources')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {Object.entries(cspPolicy.policy).map(([directive, sources]) => (
                    sources && (
                      <TableRow key={directive}>
                        <TableCell>
                          <Typography variant="body2" fontWeight="bold">
                            {directive}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
                            {Array.isArray(sources) ? sources.map((source, idx) => (
                              <Chip key={idx} label={source} size="small" variant="outlined" />
                            )) : (
                              <Chip label={sources.toString()} size="small" variant="outlined" />
                            )}
                          </Box>
                        </TableCell>
                      </TableRow>
                    )
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        )}

        {/* Violation Details Dialog */}
        <Dialog
          open={violationDialogOpen}
          onClose={() => setViolationDialogOpen(false)}
          maxWidth="md"
          fullWidth
        >
          <DialogTitle>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <ErrorIcon color="error" />
              {t('security.violationDetails')}
            </Box>
          </DialogTitle>
          <DialogContent>
            {selectedViolation && (
              <Box sx={{ mt: 1 }}>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.timestamp')}
                    </Typography>
                    <Typography variant="body1">
                      {format(new Date(selectedViolation.created_at), 'PPpp')}
                    </Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.violatedDirective')}
                    </Typography>
                    <Typography variant="body1">
                      <Chip label={selectedViolation.violated_directive} color="error" size="small" />
                    </Typography>
                  </Grid>
                  <Grid item xs={12}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.blockedUri')}
                    </Typography>
                    <Typography variant="body2" sx={{ wordBreak: 'break-all', fontFamily: 'monospace' }}>
                      {selectedViolation.blocked_uri || 'inline'}
                    </Typography>
                  </Grid>
                  <Grid item xs={12}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.sourceFile')}
                    </Typography>
                    <Typography variant="body2" sx={{ wordBreak: 'break-all', fontFamily: 'monospace' }}>
                      {selectedViolation.source_file || 'N/A'}
                    </Typography>
                  </Grid>
                  {selectedViolation.line_number && (
                    <Grid item xs={12} sm={6}>
                      <Typography variant="caption" color="text.secondary">
                        {t('security.lineNumber')}
                      </Typography>
                      <Typography variant="body1">
                        {selectedViolation.line_number}
                      </Typography>
                    </Grid>
                  )}
                  {selectedViolation.column_number && (
                    <Grid item xs={12} sm={6}>
                      <Typography variant="caption" color="text.secondary">
                        {t('security.columnNumber')}
                      </Typography>
                      <Typography variant="body1">
                        {selectedViolation.column_number}
                      </Typography>
                    </Grid>
                  )}
                  <Grid item xs={12}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.documentUri')}
                    </Typography>
                    <Typography variant="body2" sx={{ wordBreak: 'break-all', fontFamily: 'monospace' }}>
                      {selectedViolation.document_uri}
                    </Typography>
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.ipAddress')}
                    </Typography>
                    <Typography variant="body1">
                      {selectedViolation.ip_address}
                    </Typography>
                  </Grid>
                  <Grid item xs={12}>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.userAgent')}
                    </Typography>
                    <Typography variant="body2" sx={{ wordBreak: 'break-word' }}>
                      {selectedViolation.user_agent}
                    </Typography>
                  </Grid>
                </Grid>
              </Box>
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setViolationDialogOpen(false)}>
              {t('close')}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </Container>
  );
};

export default CSPDashboard;
