import React from 'react';
import { Modal, Box, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, Tooltip, IconButton, CircularProgress, Alert } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import type { EmailLogDto } from '../../../models/dtos/Comunicaciones/EmailLogDto';

interface HistorialEnviosModalProps {
  open: boolean;
  onClose: () => void;
  logs: EmailLogDto[];
  isLoading: boolean;
  error: string | null;
  titulo: string;
}

const modalStyle = {
  position: 'absolute' as 'absolute',
  top: '50%', left: '50%',
  transform: 'translate(-50%, -50%)',
  width: { xs: '95%', sm: '80%', md: '700px' },
  bgcolor: 'background.paper',
  boxShadow: 24, p: 4,
  borderRadius: 2,
};

const HistorialEnviosModal: React.FC<HistorialEnviosModalProps> = ({ open, onClose, logs, isLoading, error, titulo }) => {
  const formatDisplayDateTime = (dateString: string): string => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('es-AR', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit'
    });
  };

  return (
    <Modal open={open} onClose={onClose}>
      <Box sx={modalStyle}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h6" component="h2">{titulo}</Typography>
          <IconButton onClick={onClose}><CloseIcon /></IconButton>
        </Box>
        {isLoading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}><CircularProgress /></Box>
        ) : error ? (
          <Alert severity="error">{error}</Alert>
        ) : (
          <TableContainer component={Paper}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 'bold' }}>Fecha de Envío</TableCell>
                  <TableCell sx={{ fontWeight: 'bold' }}>Estado</TableCell>
                  <TableCell sx={{ fontWeight: 'bold' }}>Destinatario</TableCell>
                  <TableCell sx={{ fontWeight: 'bold' }}>Asunto</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {logs.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} align="center">No se han registrado envíos.</TableCell>
                  </TableRow>
                ) : (
                  logs.map((log, index) => (
                    <TableRow key={index}>
                      <TableCell>{formatDisplayDateTime(log.fechaEnvio)}</TableCell>
                      <TableCell>
                        <Tooltip title={log.estado === 'Fallido' ? (log.error || 'Error desconocido') : ''} arrow>
                          <Chip 
                            label={log.estado} 
                            color={log.estado === 'Enviado' ? 'success' : 'error'} 
                            size="small" 
                          />
                        </Tooltip>
                      </TableCell>
                      <TableCell>{log.destinatarioEmail}</TableCell>
                      <TableCell>{log.asunto}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Box>
    </Modal>
  );
};

export default HistorialEnviosModal;