import React, { useState, useEffect } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Chip from '@mui/material/Chip';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';
import Divider from '@mui/material/Divider';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { format, parseISO } from 'date-fns';
import { de } from 'date-fns/locale';
import axios from 'axios';

interface AuditLogEntry {
  id: number;
  action: string;
  edited_by: {
    usr_id: number;
    full_name: string;
    initials: string;
  } | null;
  old_values: Record<string, any> | null;
  new_values: Record<string, any> | null;
  notes: string | null;
  created_at: string;
}

interface AuditLogModalProps {
  open: boolean;
  onClose: () => void;
  requestId: number | null;
  type: 'vacation' | 'sick';
}

const AuditLogModal: React.FC<AuditLogModalProps> = ({
  open,
  onClose,
  requestId,
  type,
}) => {
  const { i18n } = useLingui();
  const [logs, setLogs] = useState<AuditLogEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (open && requestId) {
      loadAuditLog();
    }
  }, [open, requestId]);

  const loadAuditLog = async () => {
    if (!requestId) return;

    try {
      setLoading(true);
      setError('');

      const endpoint = type === 'vacation'
        ? `/zeiterfassung/vacation-requests/${requestId}/audit-log`
        : `/zeiterfassung/sick-requests/${requestId}/audit-log`;

      const response = await axios.get(endpoint);
      setLogs(response.data);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to load audit log');
    } finally {
      setLoading(false);
    }
  };

  const formatFieldName = (field: string): string => {
    const fieldNames: Record<string, string> = {
      zvr_from_date: i18n._(t`Von`),
      zvr_to_date: i18n._(t`Bis`),
      zvr_status: i18n._(t`Status`),
      zvr_notes: i18n._(t`Notizen`),
      zvr_reason: i18n._(t`Grund`),
      zsr_from_date: i18n._(t`Von`),
      zsr_to_date: i18n._(t`Bis`),
      zsr_status: i18n._(t`Status`),
      zsr_notes: i18n._(t`Notizen`),
    };
    return fieldNames[field] || field;
  };

  const formatValue = (field: string, value: any): string => {
    if (value === null || value === undefined) return '-';

    // Format dates
    if (field.includes('date') && typeof value === 'string') {
      try {
        return format(parseISO(value), 'dd.MM.yyyy', { locale: de });
      } catch {
        return value;
      }
    }

    // Format status
    if (field.includes('status')) {
      const statusLabels: Record<string, string> = {
        submitted: i18n._(t`Eingereicht`),
        approved: i18n._(t`Genehmigt`),
        rejected: i18n._(t`Abgelehnt`),
      };
      return statusLabels[value] || value;
    }

    return String(value);
  };

  const getActionLabel = (action: string): string => {
    const actionLabels: Record<string, string> = {
      created: i18n._(t`Erstellt`),
      updated: i18n._(t`Bearbeitet`),
      status_changed: i18n._(t`Status geändert`),
      deleted: i18n._(t`Gelöscht`),
    };
    return actionLabels[action] || action;
  };

  const getActionColor = (action: string) => {
    switch (action) {
      case 'created':
        return 'success';
      case 'updated':
        return 'info';
      case 'status_changed':
        return 'warning';
      case 'deleted':
        return 'error';
      default:
        return 'default';
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Trans>Änderungsverlauf</Trans>
      </DialogTitle>
      <DialogContent>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <CircularProgress />
          </Box>
        ) : error ? (
          <Alert severity="error">{error}</Alert>
        ) : logs.length === 0 ? (
          <Alert severity="info">
            <Trans>Keine Änderungen vorhanden</Trans>
          </Alert>
        ) : (
          <List sx={{ position: 'relative', pl: 2 }}>
            {/* Vertical timeline line */}
            <Box
              sx={{
                position: 'absolute',
                left: 16,
                top: 20,
                bottom: 20,
                width: 2,
                bgcolor: 'primary.light',
                opacity: 0.3,
              }}
            />
            {logs.map((log, logIndex) => {
              // Get all changed fields for this log entry
              const changedFields: Array<{ field: string; oldValue: any; newValue: any }> = [];

              if (log.old_values && log.new_values) {
                Object.keys(log.new_values).forEach((field) => {
                  const oldValue = log.old_values?.[field];
                  const newValue = log.new_values?.[field];
                  if (oldValue !== newValue) {
                    changedFields.push({ field, oldValue, newValue });
                  }
                });
              }

              return (
                <React.Fragment key={log.id}>
                  {changedFields.length > 0 ? (
                    changedFields.map((change, changeIndex) => (
                      <ListItem
                        key={`${log.id}-${change.field}`}
                        sx={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          position: 'relative',
                          mb: 2,
                          pl: 0,
                        }}
                      >
                        {/* Timeline dot */}
                        <Box
                          sx={{
                            position: 'absolute',
                            left: 8,
                            top: 8,
                            width: 16,
                            height: 16,
                            borderRadius: '50%',
                            bgcolor: 'primary.main',
                            border: '3px solid',
                            borderColor: 'background.paper',
                            zIndex: 1,
                          }}
                        />

                        <Box sx={{ flex: 1, ml: 4 }}>
                          <Paper
                            elevation={3}
                            sx={{
                              p: 2,
                              borderLeft: 4,
                              borderColor: 'primary.main',
                              background: 'linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%)',
                              transition: 'all 0.3s ease',
                              '&:hover': {
                                transform: 'translateX(4px)',
                                boxShadow: 6,
                              },
                            }}
                          >
                            {/* Header: Field name and timestamp */}
                            <Box
                              sx={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'start',
                                mb: 1,
                              }}
                            >
                              <Chip
                                label={formatFieldName(change.field)}
                                size="small"
                                color="primary"
                                sx={{ fontWeight: 'bold' }}
                              />
                              <Typography variant="caption" color="textSecondary">
                                {format(parseISO(log.created_at), 'dd.MM.yyyy HH:mm', { locale: de })}
                              </Typography>
                            </Box>

                            {/* Old → New values */}
                            <Box
                              sx={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: 1,
                                my: 1,
                                p: 1.5,
                                bgcolor: 'grey.100',
                                borderRadius: 1,
                              }}
                            >
                              <Chip
                                label={formatValue(change.field, change.oldValue)}
                                size="small"
                                sx={{
                                  bgcolor: 'error.light',
                                  color: 'error.contrastText',
                                  textDecoration: 'line-through',
                                }}
                              />
                              <Typography variant="body2" sx={{ mx: 1, fontWeight: 'bold' }}>
                                →
                              </Typography>
                              <Chip
                                label={formatValue(change.field, change.newValue)}
                                size="small"
                                sx={{
                                  bgcolor: 'success.light',
                                  color: 'success.contrastText',
                                  fontWeight: 'bold',
                                }}
                              />
                            </Box>

                            {/* Reason/notes (only show once per log entry, on first field) */}
                            {changeIndex === 0 && log.notes && (
                              <Box
                                sx={{
                                  mt: 1.5,
                                  p: 1.5,
                                  bgcolor: 'info.50',
                                  borderLeft: 3,
                                  borderColor: 'info.main',
                                  borderRadius: 1,
                                }}
                              >
                                <Typography variant="caption" fontWeight="bold" color="info.dark">
                                  Grund:
                                </Typography>
                                <Typography variant="body2" sx={{ mt: 0.5, fontStyle: 'italic' }}>
                                  "{log.notes}"
                                </Typography>
                              </Box>
                            )}

                            {/* Editor (only show once per log entry, on first field) */}
                            {changeIndex === 0 && (
                              <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                                <Typography variant="caption" color="textSecondary">
                                  Geändert von:
                                </Typography>
                                <Chip
                                  label={log.edited_by?.full_name || 'Unknown'}
                                  size="small"
                                  variant="outlined"
                                  sx={{ fontSize: '0.7rem', height: 20 }}
                                />
                              </Box>
                            )}
                          </Paper>
                        </Box>
                      </ListItem>
                    ))
                  ) : (
                    // For log entries without field changes (e.g., just notes or actions)
                    <ListItem
                      key={log.id}
                      sx={{
                        display: 'flex',
                        alignItems: 'flex-start',
                        position: 'relative',
                        mb: 2,
                        pl: 0,
                      }}
                    >
                      {/* Timeline dot */}
                      <Box
                        sx={{
                          position: 'absolute',
                          left: 8,
                          top: 8,
                          width: 16,
                          height: 16,
                          borderRadius: '50%',
                          bgcolor: 'primary.main',
                          border: '3px solid',
                          borderColor: 'background.paper',
                          zIndex: 1,
                        }}
                      />

                      <Box sx={{ flex: 1, ml: 4 }}>
                        <Paper
                          elevation={3}
                          sx={{
                            p: 2,
                            borderLeft: 4,
                            borderColor: 'primary.main',
                            background: 'linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%)',
                            transition: 'all 0.3s ease',
                            '&:hover': {
                              transform: 'translateX(4px)',
                              boxShadow: 6,
                            },
                          }}
                        >
                          {/* Header: Action and timestamp */}
                          <Box
                            sx={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'start',
                              mb: 1,
                            }}
                          >
                            <Chip
                              label={getActionLabel(log.action)}
                              color={getActionColor(log.action) as any}
                              size="small"
                              sx={{ fontWeight: 'bold' }}
                            />
                            <Typography variant="caption" color="textSecondary">
                              {format(parseISO(log.created_at), 'dd.MM.yyyy HH:mm', { locale: de })}
                            </Typography>
                          </Box>

                          {/* Reason/notes */}
                          {log.notes && (
                            <Box
                              sx={{
                                mt: 1.5,
                                p: 1.5,
                                bgcolor: 'info.50',
                                borderLeft: 3,
                                borderColor: 'info.main',
                                borderRadius: 1,
                              }}
                            >
                              <Typography variant="caption" fontWeight="bold" color="info.dark">
                                Grund:
                              </Typography>
                              <Typography variant="body2" sx={{ mt: 0.5, fontStyle: 'italic' }}>
                                "{log.notes}"
                              </Typography>
                            </Box>
                          )}

                          {/* Editor */}
                          <Box sx={{ mt: 1, display: 'flex', alignItems: 'center', gap: 0.5 }}>
                            <Typography variant="caption" color="textSecondary">
                              Geändert von:
                            </Typography>
                            <Chip
                              label={log.edited_by?.full_name || 'Unknown'}
                              size="small"
                              variant="outlined"
                              sx={{ fontSize: '0.7rem', height: 20 }}
                            />
                          </Box>
                        </Paper>
                      </Box>
                    </ListItem>
                  )}
                </React.Fragment>
              );
            })}
          </List>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>
          <Trans>Schließen</Trans>
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default AuditLogModal;
