import React, { useState, useEffect, useMemo } from 'react';
import { Box, Dialog, DialogTitle, DialogContent, IconButton, Tabs, Tab, Table, TableContainer, TableHead, TableRow, TableCell, TableBody, Paper, Chip, CircularProgress, Alert } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import type { EmailLogDto } from '../../../models/dtos/Comunicaciones/EmailLogDto';
import facturacionService from '../../../services/Suscripciones/facturacionService';

interface ResultadoEnvioModalProps {
  open: boolean;
  onClose: () => void;
  loteId: number | null;
  periodo: string;
}

const ResultadoEnvioModal: React.FC<ResultadoEnvioModalProps> = ({ open, onClose, loteId, periodo }) => {
  const [activeTab, setActiveTab] = useState(0);
  const [logs, setLogs] = useState<EmailLogDto[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open && loteId) {
      const fetchDetails = async () => {
        setLoading(true);
        setError(null);
        try {
          const data = await facturacionService.getDetallesLoteEnvio(loteId);
          setLogs(data);
        } catch (err) {
          setError('No se pudieron cargar los detalles del envío.');
        } finally {
          setLoading(false);
        }
      };
      fetchDetails();
    }
  }, [open, loteId]);

  const filteredLogs = useMemo(() => {
    if (activeTab === 1) return logs.filter(log => log.estado === 'Enviado');
    if (activeTab === 2) return logs.filter(log => log.estado === 'Fallido');
    return logs; // Tab 0 es 'Todos'
  }, [logs, activeTab]);

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle>
        Detalle del Lote de Envío - Período {periodo}
        <IconButton onClick={onClose} sx={{ position: 'absolute', right: 8, top: 8 }}><CloseIcon /></IconButton>
      </DialogTitle>
      <DialogContent dividers>
        <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
          <Tabs value={activeTab} onChange={(_e, newValue) => setActiveTab(newValue)}>
            <Tab label={`Todos (${logs.length})`} />
            <Tab label={`Enviados (${logs.filter(l => l.estado === 'Enviado').length})`} />
            <Tab label={`Fallidos (${logs.filter(l => l.estado === 'Fallido').length})`} />
          </Tabs>
        </Box>

        {loading ? <CircularProgress /> : error ? <Alert severity="error">{error}</Alert> :
        <TableContainer component={Paper}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>Destinatario</TableCell>
                <TableCell>Asunto</TableCell>
                <TableCell>Estado</TableCell>
                <TableCell>Detalle del Error</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredLogs.map((log, index) => (
                <TableRow key={index}>
                  <TableCell>{log.destinatarioEmail}</TableCell>
                  <TableCell>{log.asunto}</TableCell>
                  <TableCell><Chip label={log.estado} color={log.estado === 'Enviado' ? 'success' : 'error'} size="small" /></TableCell>
                  <TableCell sx={{ color: 'error.main' }}>{log.error || '-'}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
        }
      </DialogContent>
    </Dialog>
  );
};

export default ResultadoEnvioModal;