"use client"

import { useState } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  Chip,
  IconButton,
  Divider,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Paper,
  Collapse,
} from "@mui/material"
import {
  Close as CloseIcon,
  Refresh as RefreshIcon,
  ExpandMore as ExpandMoreIcon,
  ExpandLess as ExpandLessIcon,
  InsertDriveFile as FileIcon,
  PictureAsPdf as PdfIcon,
  Description as DocIcon,
  TableChart as ExcelIcon,
} from "@mui/icons-material"
import { type IEmail, EmailStatus, type IEmailAttachment } from "@/shared/types/email"
import { formatDateTime } from "@/utils/format-time"

interface EmailDetailModalProps {
  open: boolean
  email: IEmail | null
  onClose: () => void
  onResend: (emailId: string) => void
}

export default function EmailDetailModal({ open, email, onClose, onResend }: EmailDetailModalProps) {
  const [showLogs, setShowLogs] = useState(false)

  if (!email) {
    return null
  }

  const getStatusChip = (status: EmailStatus) => {
    let color: "success" | "warning" | "error" | "default" = "default"
    let label = ""

    switch (status) {
      case EmailStatus.ENVOYE:
        color = "success"
        label = "Envoyé"
        break
      case EmailStatus.EN_ATTENTE:
        color = "warning"
        label = "En attente"
        break
      case EmailStatus.ECHEC:
        color = "error"
        label = "Échec"
        break
      default:
        color = "default"
        label = status
    }

    return <Chip label={label} color={color} size="small" />
  }

  const getFileIcon = (attachment: IEmailAttachment) => {
    if (attachment.type.includes("pdf")) {
      return <PdfIcon color="error" />
    } else if (attachment.type.includes("word")) {
      return <DocIcon color="primary" />
    } else if (attachment.type.includes("excel") || attachment.type.includes("spreadsheet")) {
      return <ExcelIcon color="success" />
    } else {
      return <FileIcon color="action" />
    }
  }

  const handleDownload = (attachment: IEmailAttachment) => {
    console.log("Downloading attachment:", attachment.nom)
    // Implement download logic here
    window.open(attachment.url, "_blank")
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <Typography variant="h6" component="div">
            {email.objet}
          </Typography>
          {getStatusChip(email.status)}
        </Box>
        <IconButton aria-label="close" onClick={onClose} size="small">
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent dividers>
        <Box sx={{ mb: 2 }}>
          <Typography variant="body2" color="text.secondary">
            De: Service RH &lt;rh@entreprise.com&gt;
          </Typography>
          <Typography variant="body2" color="text.secondary">
            À: {email.destinataire} &lt;{email.destinataireEmail}&gt;
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Date: {formatDateTime(email.dateHeure)}
          </Typography>
        </Box>

        <Divider sx={{ my: 2 }} />

        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" gutterBottom>
            Contenu
          </Typography>
          <Paper
            variant="outlined"
            sx={{ p: 2, bgcolor: "background.default", minHeight: "200px" }}
            dangerouslySetInnerHTML={{ __html: email.contenu }}
          />
        </Box>

        {email.pieceJointes && email.pieceJointes.length > 0 && (
          <Box sx={{ mb: 3 }}>
            <Typography variant="subtitle1" gutterBottom>
              Pièces jointes
            </Typography>
            <List dense>
              {email.pieceJointes.map((attachment) => (
                <ListItem
                  key={attachment.id}
                  button
                  onClick={() => handleDownload(attachment)}
                  sx={{
                    border: "1px solid",
                    borderColor: "divider",
                    borderRadius: 1,
                    mb: 1,
                  }}
                >
                  <ListItemIcon>{getFileIcon(attachment)}</ListItemIcon>
                  <ListItemText
                    primary={attachment.nom}
                    secondary={`${attachment.taille}`}
                    primaryTypographyProps={{ variant: "body2" }}
                  />
                </ListItem>
              ))}
            </List>
          </Box>
        )}

        {email.status === EmailStatus.ECHEC && email.logsErreur && (
          <Box sx={{ mb: 2 }}>
            <Button
              startIcon={showLogs ? <ExpandLessIcon /> : <ExpandMoreIcon />}
              onClick={() => setShowLogs(!showLogs)}
              color="error"
              variant="text"
              sx={{ mb: 1 }}
            >
              {showLogs ? "Masquer les logs d'erreur" : "Afficher les logs d'erreur"}
            </Button>
            <Collapse in={showLogs}>
              <Paper
                variant="outlined"
                sx={{
                  p: 2,
                  bgcolor: "error.lighter",
                  fontFamily: "monospace",
                  whiteSpace: "pre-wrap",
                  fontSize: "0.8rem",
                  color: "error.dark",
                  maxHeight: "200px",
                  overflow: "auto",
                }}
              >
                {email.logsErreur}
              </Paper>
            </Collapse>
          </Box>
        )}
      </DialogContent>

      <DialogActions>
        {email.status === EmailStatus.ECHEC && (
          <Button startIcon={<RefreshIcon />} variant="contained" color="primary" onClick={() => onResend(email.id)}>
            Relancer
          </Button>
        )}
        <Button onClick={onClose} variant="outlined">
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  )
}

