// email-history-detail.tsx
"use client"

import { useState } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  IconButton,
  Box,
  Chip,
  Paper,
  Collapse,
} from "@mui/material"
import {
  Close as CloseIcon,
  ExpandMore as ExpandMoreIcon,
  ExpandLess as ExpandLessIcon,
  Refresh as RefreshIcon,
} from "@mui/icons-material"
import { EmailStatus, type IEmailHistory } from "@/shared/types/email-history"
import { formatDateTime } from "@/utils/format-time"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface EmailHistoryDetailProps {
  open: boolean
  emailHistory: IEmailHistory | null
  onClose: () => void
  onRetry?: (id: string) => void
  onCancel?: (id: string) => void
}

export default function EmailHistoryDetail({
  open,
  emailHistory,
  onClose,
  onRetry,
  onCancel,
}: EmailHistoryDetailProps) {
  const [showLogs, setShowLogs] = useState(false)

  if (!emailHistory) {
    return null
  }

  const handleRetry = () => {
    if (onRetry) {
      onRetry(emailHistory.id)
      onClose()
    }
  }

  const handleCancel = () => {
    if (onCancel) {
      onCancel(emailHistory.id)
      onClose()
    }
  }

  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.ECHEC:
        color = "error"
        label = "Échec"
        break
      case EmailStatus.PLANIFIE:
        color = "warning"
        label = "Planifié"
        break
      default:
        color = "default"
        label = status
    }

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

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 4,
          overflow: "hidden",
        },
      }}
    >
      <DialogTitle
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          backgroundColor: "primary.main",
          color: "white",
          fontWeight: "600",
          padding: "16px 24px",
          borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <Typography variant="h6" sx={{ fontSize: "1.25rem", fontWeight: "bold", color: "white" }}>
          Détails de l&#39;email
          </Typography>
          {getStatusChip(emailHistory.status)}
        </Box>
        <IconButton aria-label="close" onClick={onClose} size="small" sx={{ color: "white" }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent
        dividers
        sx={{
          backgroundColor: "#fafafa",
          padding: "24px",
          display: "flex",
          flexDirection: "column",
          gap: "16px",
        }}
      >
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" gutterBottom>
            Informations générales
          </Typography>
          <Box sx={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 2 }}>
            <Typography variant="body2" color="text.secondary">
              Modèle utilisé:
            </Typography>
            <Typography variant="body2">{emailHistory.templateTitre}</Typography>

            <Typography variant="body2" color="text.secondary">
            Date d&#39;envoi:
            </Typography>
            <Typography variant="body2">{formatDateTime(emailHistory.dateEnvoi)}</Typography>

            <Typography variant="body2" color="text.secondary">
              Destinataires:
            </Typography>
            <Typography variant="body2">{emailHistory.destinataires}</Typography>

            <Typography variant="body2" color="text.secondary">
              Statut:
            </Typography>
            <Box>{getStatusChip(emailHistory.status)}</Box>
          </Box>
        </Box>

        <ConditionalComponent isValid={!!emailHistory.details}>
          <Box sx={{ mb: 3 }}>
            <Typography variant="subtitle1" gutterBottom>
              Détails supplémentaires
            </Typography>
            <Paper variant="outlined" sx={{ p: 2 }}>
              <Typography variant="body2">{emailHistory.details}</Typography>
            </Paper>
          </Box>
        </ConditionalComponent>

        <ConditionalComponent isValid={emailHistory.status === EmailStatus.ECHEC && !!emailHistory.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",
                }}
              >
                {emailHistory.logsErreur}
              </Paper>
            </Collapse>
          </Box>
        </ConditionalComponent>
      </DialogContent>

      <DialogActions sx={{ padding: "16px 24px", backgroundColor: "#fafafa" }}>
        <ConditionalComponent isValid={emailHistory.status === EmailStatus.ECHEC && !!onRetry}>
          <Button
            startIcon={<RefreshIcon />}
            color="primary"
            onClick={handleRetry}
            variant="outlined"
            sx={{
              borderRadius: "8px",
              padding: "8px 16px",
              color: "primary.main",
              borderColor: "primary.main",
              "&:hover": {
                borderColor: "primary.dark",
                color: "primary.dark",
              },
              mr: 1,
            }}
          >
            Réessayer l&#39;envoi
          </Button>
        </ConditionalComponent>

        <ConditionalComponent isValid={emailHistory.status === EmailStatus.PLANIFIE && !!onCancel}>
          <Button
            color="error"
            onClick={handleCancel}
            variant="outlined"
            sx={{
              borderRadius: "8px",
              padding: "8px 16px",
              color: "error.main",
              borderColor: "error.main",
              "&:hover": {
                borderColor: "error.dark",
                color: "error.dark",
              },
              mr: 1,
            }}
          >
           Annuler l&#39;envoi planifié
          </Button>
        </ConditionalComponent>

        <Button
          onClick={onClose}
          variant="contained"
          sx={{
            borderRadius: "8px",
            padding: "8px 16px",
            backgroundColor: "primary.main",
            "&:hover": {
              backgroundColor: "primary.dark",
            },
            boxShadow: 2,
          }}
        >
          Fermer
        </Button>
      </DialogActions>
    </Dialog>
  )
}