"use client"

import Checkbox from "@mui/material/Checkbox"
import TableCell from "@mui/material/TableCell"
import SvgColor from "@/shared/components/svg-color"
import type { TableColumn } from "@/shared/types/common"
import { type IEmailHistory, EmailStatus } from "@/shared/types/email-history"
import { ContratStyledRow } from "@/shared/sections/contract/styles"
import { formatDateTime } from "@/utils/format-time"
import { Chip, IconButton, Tooltip, Box } from "@mui/material"
import { Visibility as VisibilityIcon, Refresh as RefreshIcon, Cancel as CancelIcon } from "@mui/icons-material"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

type Props = {
  handleViewDetails: (emailHistory: IEmailHistory) => void
  handleRetry?: (emailHistory: IEmailHistory) => void
  handleCancel?: (emailHistory: IEmailHistory) => void
  selected: boolean
  row: IEmailHistory
  dense: boolean
  onSelectRow: VoidFunction
  columns: TableColumn[]
}

const getStatusColor = (status: EmailStatus) => {
  switch (status) {
    case EmailStatus.ENVOYE:
      return {
        color: "success",
        backgroundColor: "success.lighter",
        borderColor: "success.light",
      }
    case EmailStatus.PLANIFIE:
      return {
        color: "warning",
        backgroundColor: "warning.lighter",
        borderColor: "warning.light",
      }
    case EmailStatus.ECHEC:
      return {
        color: "error",
        backgroundColor: "error.lighter",
        borderColor: "error.light",
      }
    default:
      return {
        color: "default",
        backgroundColor: "grey.200",
        borderColor: "grey.300",
      }
  }
}

export default function EmailHistoryTableRow({
  dense,
  row,
  handleViewDetails,
  handleRetry,
  handleCancel,
  selected,
  onSelectRow,
  columns,
}: Props) {
  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "dateEnvoi":
        return formatDateTime(value)
      case "status":
        const statusColors = getStatusColor(value as EmailStatus)
        let label = ""
        switch (value) {
          case EmailStatus.ENVOYE:
            label = "Envoyé"
            break
          case EmailStatus.PLANIFIE:
            label = "Planifié"
            break
          case EmailStatus.ECHEC:
            label = "Échec"
            break
          default:
            label = value
        }
        return (
          <Chip
            label={label}
            size="small"
            variant="outlined"            
            sx={{
              '&.MuiChip-root': {
              borderRadius: '8px',
              padding: '9px 0',
              height: '100%',
              width: '100px',
              },
              color: `${statusColors.color}.main`,
              backgroundColor: statusColors.backgroundColor,
              borderColor: statusColors.borderColor,
              fontWeight: "medium",
            }}
          />
        )
      default:
        return value
    }
  }

  return (
    <ContratStyledRow hover style={{ cursor: "pointer" }}>
      {columns
        .filter((column) => column.id !== "isArchive")
        .map((column: any,index:number) => (
          <TableCell
            onDoubleClick={() => handleViewDetails(row)}
            key={column.id}
            align={column.align}
            sx={{ whiteSpace: "nowrap", py: dense ? 0 : 2,
              ...(index === 0 && {
                position: 'relative',
              })
            }}
          >
            <ConditionalComponent isValid={index === 0}>
              <SvgColor
                src="/assets/icons/ic_border.svg"
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: -4,
                  height: '100%',
                  color: row.status === EmailStatus.ECHEC ? "error.main" : "primary.main",
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IEmailHistory])}
          </TableCell>
        ))}

      <TableCell sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <Box sx={{ display: "flex", gap: 1 }}>
          <ConditionalComponent isValid={row.status === EmailStatus.ECHEC && !!handleRetry}>
            <CustomTooltip arrow title="Réessayer l'envoi">
              <IconButton size="small" onClick={() => handleRetry!(row)} sx={{ color: "warning.main" }}>
                <RefreshIcon fontSize="small" />
              </IconButton>
            </CustomTooltip>
          </ConditionalComponent>

          <ConditionalComponent isValid={row.status === EmailStatus.PLANIFIE && !!handleCancel}>
            <CustomTooltip arrow title="Annuler l'envoi">
              <IconButton size="small" onClick={() => handleCancel!(row)} sx={{ color: "error.main" }}>
                <CancelIcon fontSize="small" />
              </IconButton>
            </CustomTooltip>
          </ConditionalComponent>
        </Box>
      </TableCell>
    </ContratStyledRow>
  )
}
