"use client"

import React from "react"
import { Checkbox, TableCell, IconButton, MenuItem, Tooltip, Chip, Stack } from "@mui/material"
import { Edit, Send, MoreVert } from "@mui/icons-material"
import SvgColor from "@/shared/components/svg-color"
import type { TableColumn } from "@/shared/types/common"
import { type INotification, NotificationCategory, DeliveryType, NotificationStatus } from "@/shared/types/notification"
import { MenuPopover } from "../components/menu-popover"
import { ContratStyledRow, StatusChip } from "@/shared/sections/contract/styles"
import { AntSwitch } from "@/shared/components/table/styles"
import { useTheme } from '@mui/material/styles';
import StatusMenu from "@/shared/components/table/StatusMenu"
import { StyledMenuItem } from "@/shared/theme/css"
import TableActionColumn from "@/shared/components/table/table-action-column"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface NotificationTableRowProps {
  row: INotification
  dense: boolean
  selected: boolean
  onSelectRow: () => void
  columns: TableColumn[]
  handleEdit: (id: string) => void
  handleCopy: (id: string) => void
  handleDetails: (id: string) => void
  onStatusChange: (row: INotification, newStatus: string, field: keyof INotification) => void
}

const TOOLTIP_TITLES = {
  edit: 'Modifier notification',
  duplicate: 'Copier notification',
  active: 'Notification active',
  inactive: 'Notification inactive',
};
export default function NotificationTableRow({
  row,
  dense,
  selected,
  onSelectRow,
  columns,
  handleEdit,
  handleCopy,
  handleDetails,
  onStatusChange,
}: NotificationTableRowProps) {
  const theme = useTheme();
  const [openPopover, setOpenPopover] = React.useState<HTMLElement | null>(null)

  const handleOpenPopover = (event: React.MouseEvent<HTMLElement>) => {
    setOpenPopover(event.currentTarget)
  }

  const handleClosePopover = () => {
    setOpenPopover(null)
  }

  const handleToggleActive = () => {
    onStatusChange(row, String(!row.isActive), "isActive" as keyof INotification)
  }

  const NotificationStatusOptions = [
    { value: NotificationStatus.ARCHIVED, label: "Archivée" },
    { value: NotificationStatus.DELETED, label: "Supprimé" },
    { value: NotificationStatus.PENDING, label: "En attente" },
    { value: NotificationStatus.READ, label: "Lu" },
    { value: NotificationStatus.SENT, label: "Envoyée" },
    { value: NotificationStatus.UNREAD, label: "Non Lu" },
  ];

  // Tronquer le message s'il est trop long
  const truncateMessage = (message: string, maxLength = 50) => {
    return message.length > maxLength ? `${message.substring(0, maxLength)}...` : message
  }

  // Déterminer la couleur de la bordure en fonction du type de notification
  const getBorderColor = () => {
    switch (row.category) {
      case NotificationCategory.ALERTE:
        return "error.main"
      case NotificationCategory.RAPPEL:
        return "warning.main"
      case NotificationCategory.INFO:
        return "info.main"
      case NotificationCategory.MAINTENANCE:
        return "secondary.main"
      case NotificationCategory.MISE_A_JOUR:
        return "success.main"
      default:
        return "primary.main"
    }
  }

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "createdAt":
        return value as string
      case "deliveryType":
        return value
      case "category":
        return value
      case "status":
        return (
          <StatusMenu
            value={value}
            options={NotificationStatusOptions}
            onChange={(newStatus) => onStatusChange(row, newStatus, 'status')}
            chipComponent={StatusChip}
            disabled
          />
        )
      case "message":
        return truncateMessage(value as string)
      case "recipients":
        return Array.isArray(value) ? value.join(", ") : (value as string)
      default:
        return value
    }
  }

  return (
    <ContratStyledRow hover style={{ cursor: "pointer" }}>

      {columns
        .filter((column) => column.id !== "actions")
        .map((column: any,index:number) => (
          <TableCell
            onDoubleClick={() => handleDetails(row.id)}
            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: getBorderColor(),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof INotification])}
          </TableCell>
        ))}

      <TableCell sx={{ px: 1, whiteSpace: 'nowrap' }}
      >
        <Stack direction="row" spacing={1} alignItems="center">

          <TableActionColumn
            handleEdit={() => handleEdit(row.id)}
            onToggle={handleToggleActive}
            isActive={row.isActive}
            tooltipTitles={TOOLTIP_TITLES}
          />

          <Tooltip title="Plus d'actions">
            <IconButton color="inherit" onClick={handleOpenPopover} size="small">
              <MoreVert fontSize="small" />
            </IconButton>
          </Tooltip>

        </Stack>
      </TableCell>

      <MenuPopover
        open={Boolean(openPopover)}
        anchorEl={openPopover}
        onClose={handleClosePopover}
        arrow="right-top"
      >
        <StyledMenuItem
          onClick={() => {
            onStatusChange(row, NotificationStatus.SENT, "status")
            handleClosePopover()
          }}
        >
          <Send sx={{ mr: 1 }} />
          Envoyer
        </StyledMenuItem>
        <StyledMenuItem
          onClick={() => {
            onStatusChange(
              row,
              row.status === NotificationStatus.READ ? NotificationStatus.UNREAD : NotificationStatus.READ,
              "status",
            )
            handleClosePopover()
          }}
        >
          {row.status === NotificationStatus.READ ? "Marquer comme non lu" : "Marquer comme lu"}
        </StyledMenuItem>
      </MenuPopover>
    </ContratStyledRow>
  )
}
