import { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  TextField,
  MenuItem,
} from '@mui/material';
import {
  Refresh as RefreshIcon,
  Download as DownloadIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import { apiJson, apiFetch } from '../lib/api';
import { logger } from '../lib/logger';

interface SessionAuditLog {
  id: number;
  user_id: number;
  username?: string;
  session_id?: string;
  event: string;
  ip_address?: string;
  user_agent?: string;
  metadata: Record<string, unknown>;
  timestamp: string;
}

interface SyncAuditLog {
  id: number;
  sync_job_id: number;
  entity_type: string;
  entity_id: string;
  action: string;
  status: string;
  error_message?: string;
  metadata: Record<string, unknown>;
  timestamp: string;
  resolution_status?: string;
}

const AuditPage: React.FC = () => {
  const { t } = useI18n();
  const [activeTab, setActiveTab] = useState<'session' | 'sync'>('session');
  const [sessionLogs, setSessionLogs] = useState<SessionAuditLog[]>([]);
  const [syncLogs, setSyncLogs] = useState<SyncAuditLog[]>([]);
  const [, setLoading] = useState(false);
  
  // Filter state
  const [eventFilter, setEventFilter] = useState<string>('all');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  
  const [selectedLog, setSelectedLog] = useState<SessionAuditLog | SyncAuditLog | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);

  const fetchAuditLogs = useCallback(async () => {
    setLoading(true);
    try {
      const filters = new URLSearchParams();
      if (eventFilter !== 'all') filters.append('event_type', eventFilter);
      if (dateFrom) filters.append('from', dateFrom);
      if (dateTo) filters.append('to', dateTo);

      const endpoint = activeTab === 'session' ? '/audit/logs' : '/audit/sync-logs';
      const data = await apiJson<SessionAuditLog[] | SyncAuditLog[]>(endpoint + '?' + filters.toString());
      
      if (activeTab === 'session') {
        setSessionLogs(data as SessionAuditLog[]);
      } else {
        setSyncLogs(data as SyncAuditLog[]);
      }
    } catch (error) {
      logger.error('Failed to fetch audit logs:', error);
    } finally {
      setLoading(false);
    }
  }, [activeTab, eventFilter, dateFrom, dateTo]);

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

  const handleExport = async () => {
    try {
      const response = await apiFetch('/audit/export');
      if (!response.ok) throw new Error('Export failed');
      
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `audit-logs-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      logger.error('Failed to export:', error);
    }
  };

  const eventLabels: Record<string, string> = {
    login: t('audit.userLogin'),
    logout: t('audit.userLogout'),
    mfa_enabled: t('audit.mfaEnabled'),
    mfa_disabled: t('audit.mfaDisabled'),
    password_changed: t('audit.passwordChanged'),
    full_sync: t('audit.fullSync'),
    incremental_sync: t('audit.incrementalSync'),
    partial_sync: t('audit.partialSync'),
    manual_sync: t('audit.manualSync'),
  };

  const getStatusColor = (status: string): 'default' | 'error' | 'warning' | 'success' => {
    if (status === 'completed' || status === 'success' || status === 'resolved') return 'success';
    if (status === 'failed' || status === 'error') return 'error';
    if (status === 'pending' || status === 'running') return 'warning';
    return 'default';
  };

  const logs = activeTab === 'session' ? sessionLogs : syncLogs;
  const filteredLogs = logs.filter(log => {
    if (activeTab === 'session') {
      const sessionLog = log as SessionAuditLog;
      if (eventFilter !== 'all' && sessionLog.event !== eventFilter) return false;
    } else {
      const syncLog = log as SyncAuditLog;
      if (eventFilter !== 'all' && syncLog.action !== eventFilter) return false;
    }
    if (dateFrom && new Date(log.timestamp) < new Date(dateFrom)) return false;
    if (dateTo && new Date(log.timestamp) > new Date(dateTo)) return false;
    return true;
  });

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ mb: 3 }}>
        <Typography variant="h4">{t('audit.title')}</Typography>
      </Box>

      <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mb: 3 }}>
        {[
          { id: 'session', label: t('audit.loginEvents') },
          { id: 'sync', label: t('audit.syncEvents') },
        ].map((tab) => (
          <Button
            key={tab.id}
            variant={activeTab === tab.id ? 'contained' : 'outlined'}
            onClick={() => setActiveTab(tab.id as 'session' | 'sync')}
            sx={{ minWidth: 150 }}
          >
            {tab.label}
          </Button>
        ))}
      </Box>

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6">{t('audit.filters')}</Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>
              <Button
                variant="outlined"
                startIcon={<DownloadIcon />}
                onClick={handleExport}
              >
                {t('audit.exportCsv')}
              </Button>
              <Button
                variant="contained"
                startIcon={<RefreshIcon />}
                onClick={fetchAuditLogs}
              >
                {t('common.refresh')}
              </Button>
            </Box>
          </Box>

          <Grid container spacing={2}>
            <Grid item xs={12} md={3}>
              <TextField
                fullWidth
                select
                label={t('audit.eventType')}
                value={eventFilter}
                onChange={(e) => setEventFilter(e.target.value)}
              >
                <MenuItem value="all">{t('audit.allEvents')}</MenuItem>
                {activeTab === 'session' ? (
                  <>
                    <MenuItem value="login">{t('audit.userLogin')}</MenuItem>
                    <MenuItem value="logout">{t('audit.userLogout')}</MenuItem>
                    <MenuItem value="mfa_enabled">{t('audit.mfaEnabled')}</MenuItem>
                    <MenuItem value="mfa_disabled">{t('audit.mfaDisabled')}</MenuItem>
                  </>
                ) : (
                  <>
                    <MenuItem value="full_sync">{t('audit.fullSync')}</MenuItem>
                    <MenuItem value="incremental_sync">{t('audit.incrementalSync')}</MenuItem>
                    <MenuItem value="partial_sync">{t('audit.partialSync')}</MenuItem>
                    <MenuItem value="manual_sync">{t('audit.manualSync')}</MenuItem>
                  </>
                )}
              </TextField>
            </Grid>
            <Grid item xs={6} md={3}>
              <TextField
                fullWidth
                type="date"
                label={t('audit.fromDate')}
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
            <Grid item xs={6} md={3}>
              <TextField
                fullWidth
                type="date"
                label={t('audit.toDate')}
                value={dateTo}
                onChange={(e) => setDateTo(e.target.value)}
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            {t('audit.auditLogs')} ({filteredLogs.length} {t('audit.records')})
          </Typography>
          
          <TableContainer sx={{ maxHeight: 600 }}>
            <Table stickyHeader>
              <TableHead>
                <TableRow>
                      <TableCell>{t('audit.colId')}</TableCell>
                  {activeTab === 'session' ? (
                    <>
                      <TableCell>{t('audit.colUser')}</TableCell>
                      <TableCell>{t('audit.colEvent')}</TableCell>
                      <TableCell>{t('audit.colIpAddress')}</TableCell>
                      <TableCell>{t('audit.colUserAgent')}</TableCell>
                    </>
                  ) : (
                    <>
                      <TableCell>{t('audit.colJobId')}</TableCell>
                      <TableCell>{t('audit.colEntityType')}</TableCell>
                      <TableCell>{t('audit.colEntityId')}</TableCell>
                      <TableCell>{t('audit.colAction')}</TableCell>
                      <TableCell>{t('audit.colStatus')}</TableCell>
                    </>
                  )}
                  <TableCell>{t('audit.colTimestamp')}</TableCell>
                  <TableCell>{t('audit.colActions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {filteredLogs.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={activeTab === 'session' ? 7 : 8} align="center">
                      <Typography variant="body2" color="textSecondary">
                        {t('audit.noLogs')}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredLogs.map((log: SessionAuditLog | SyncAuditLog) => (
                    <TableRow key={log.id} hover>
                      <TableCell>{log.id}</TableCell>
                      {activeTab === 'session' ? (
                        <>
                          <TableCell>{(log as SessionAuditLog).username || `User ${(log as SessionAuditLog).user_id}`}</TableCell>
                          <TableCell>
                            <Chip 
                              label={eventLabels[(log as SessionAuditLog).event] || (log as SessionAuditLog).event} 
                              size="small"
                              color={'event' in log && (log as SessionAuditLog).event === 'login' ? 'success' : (log as SessionAuditLog).event === 'logout' ? 'primary' : 'default'}
                            />
                          </TableCell>
                          <TableCell>{(log as SessionAuditLog).ip_address || '-'}</TableCell>
                          <TableCell sx={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {(log as SessionAuditLog).user_agent || '-'}
                          </TableCell>
                        </>
                      ) : (
                        <>
                          <TableCell>{(log as SyncAuditLog).sync_job_id}</TableCell>
                          <TableCell>{(log as SyncAuditLog).entity_type}</TableCell>
                          <TableCell>{(log as SyncAuditLog).entity_id}</TableCell>
                          <TableCell>{(log as SyncAuditLog).action}</TableCell>
                          <TableCell>
                            <Chip 
                              label={(log as SyncAuditLog).resolution_status || (log as SyncAuditLog).status} 
                              size="small"
                              color={getStatusColor((log as SyncAuditLog).resolution_status || (log as SyncAuditLog).status)}
                            />
                          </TableCell>
                        </>
                      )}
                      <TableCell>
                        {new Date(log.timestamp).toLocaleString()}
                      </TableCell>
                      <TableCell>
                        <Button
                          size="small"
                          variant="outlined"
                          onClick={() => {
                            setSelectedLog(log);
                            setDetailDialogOpen(true);
                          }}
                        >
                          {t('audit.details')}
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </CardContent>
      </Card>

      <Dialog open={detailDialogOpen} onClose={() => setDetailDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>
          {t('audit.detailsTitle')}
        </DialogTitle>
        <DialogContent>
          {selectedLog && (
            <Box>
              <Grid container spacing={2}>
                <Grid item xs={6}>
                    <Typography variant="subtitle2" color="textSecondary">{t('audit.colId')}</Typography>
                  <Typography variant="body1">{selectedLog.id}</Typography>
                </Grid>
                <Grid item xs={6}>
                  <Typography variant="subtitle2" color="textSecondary">{t('audit.colTimestamp')}</Typography>
                  <Typography variant="body1">
                    {new Date(selectedLog.timestamp).toLocaleString()}
                  </Typography>
                </Grid>
                
                {activeTab === 'session' && (
                  <>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colUser')}</Typography>
                      <Typography variant="body1">{(selectedLog as SessionAuditLog).username || `User ${(selectedLog as SessionAuditLog).user_id}`}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colEvent')}</Typography>
                      <Typography variant="body1">{eventLabels[(selectedLog as SessionAuditLog).event] || (selectedLog as SessionAuditLog).event}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colIpAddress')}</Typography>
                      <Typography variant="body1">{(selectedLog as SessionAuditLog).ip_address || '-'}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colUserAgent')}</Typography>
                      <Typography variant="body2">{(selectedLog as SessionAuditLog).user_agent || '-'}</Typography>
                    </Grid>
                  </>
                )}
                
                {activeTab === 'sync' && (
                  <>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colJobId')}</Typography>
                      <Typography variant="body1">{(selectedLog as SyncAuditLog).sync_job_id}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colEntityType')}</Typography>
                      <Typography variant="body1">{(selectedLog as SyncAuditLog).entity_type}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colEntityId')}</Typography>
                      <Typography variant="body1">{(selectedLog as SyncAuditLog).entity_id}</Typography>
                    </Grid>
                    <Grid item xs={6}>
                      <Typography variant="subtitle2" color="textSecondary">{t('audit.colAction')}</Typography>
                      <Typography variant="body1">{(selectedLog as SyncAuditLog).action}</Typography>
                    </Grid>
                  </>
                )}
                
                <Grid item xs={12}>
                  <Typography variant="subtitle2" color="textSecondary">{t('audit.metadata')}</Typography>
                  <Box sx={{ 
                    bgcolor: '#f5f5f5', 
                    p: 2, 
                    borderRadius: 1, 
                    maxHeight: 200, 
                    overflow: 'auto',
                    fontFamily: 'monospace',
                    fontSize: '0.85rem',
                  }}>
                    <pre style={{ margin: 0 }}>
                      {JSON.stringify(selectedLog.metadata, null, 2)}
                    </pre>
                  </Box>
                </Grid>
              </Grid>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>{t('common.close')}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AuditPage;
