import React, { useState } from 'react';
import { Checkbox, TableCell, Chip, Stack, Typography, IconButton, TextField, Dialog, DialogTitle, DialogContent, DialogActions, Button, Select, MenuItem, FormControl, InputLabel, useTheme, Tooltip } from '@mui/material';
import { ICandidature, CandidatureStatut, CandidatureTab, CandidatureContratStatut, StatutRendezVous } from '@/shared/types/candidature';
import { TableColumn } from '@/shared/types/common';
import TableActionColumn from '@/shared/components/table/table-action-column';
import SendFormModal from '../send-form-modal';
import SendEmailModal from '../send-email-modal';
import ScheduleRdvModal from '../schedule-rdv-modal';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCircleCheck } from '@fortawesome/free-regular-svg-icons';
import { faEnvelope, faFileLines, faPlus, faCalendarDays, faUserClock } from '@fortawesome/free-solid-svg-icons';
import { ContratStyledRow } from '@/shared/sections/contract/styles';
import SvgColor from '@/shared/components/svg-color';
import { styled } from '@mui/system';
import { ActionsIconButton } from '@/shared/theme/css';
import StatusChangeDialog, { StatusOption } from '@/shared/components/dialog/StatusChangeDialog';
import CustomDatePicker from '@/shared/components/date-picker/customDate';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import dayjs from 'dayjs';
import 'dayjs/locale/fr';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import StatusMenu from '@/shared/components/table/StatusMenu';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';

interface CandidatureTableRowProps {
  row: ICandidature;
  selected: boolean;
  onSelectRow: VoidFunction;
  handleEdit: (item: ICandidature) => void;
  handleView: (item: ICandidature) => void;
  columns: TableColumn[];
  dense: boolean;
  activeTab?: CandidatureTab;
  onStatusChange: (row: ICandidature, newStatus: string, field: keyof ICandidature, reason?: string) => void;
  onCreateRdvSemaine?: (candidature: ICandidature) => void;
  onScheduleRdv?: (candidateId: string, rdvDateTime: string) => Promise<void>;
  onMarkAsAbsent?: (candidateId: string) => Promise<void>;
  onReplanifyRdv?: (candidateId: string, rdvDateTime: string) => Promise<void>;
  onSendForm?: (candidateId: string, formId: string, observation?: string) => Promise<void>;
  useBackend?: boolean;
}

const StyledChip = styled(Chip)(({ status }: { status: string }) => ({
  '&.MuiChip-root': {
    fontWeight: 500,
    borderRadius: '8px',
    padding: '9px 0',
    height: '100%',
    width: '100%',
    ...(status === CandidatureStatut.ATraiter && {
      backgroundColor: '#746CD4',
      color: '#FFFFFF',
    }),
    ...(status === CandidatureStatut.EnCours && {
      backgroundColor: '#E3F2FD',
      color: '#0288d1',
    }),
    ...(status === CandidatureStatut.Retenu && {
      backgroundColor: '#FFF7E0',
      color: '#B78103',
    }),
    ...((status === CandidatureStatut.Valide || status === CandidatureContratStatut.Signe) && {
      backgroundColor: '#E9FBF0',
      color: '#36B37E',
    }),
    ...((status === CandidatureStatut.Refuse || status === CandidatureContratStatut.NonSigne) && {
      backgroundColor: '#FFE1E1',
      color: '#d32f2f',
    }),
    ...(status === CandidatureStatut.Blackliste && {
      backgroundColor: '#2D2D2D',
      color: '#FFFFFF',
    }),
    ...(status === CandidatureStatut.Absent && {
      backgroundColor: '#F5F5F5',
      color: '#757575',
    }),
    ...(status === CandidatureStatut.Replanifiee && {
      backgroundColor: '#FFFF99',
      color: '#757575',
    }),
  },
}));

export default function CandidatureTableRow({
  row,
  selected,
  onSelectRow,
  handleEdit,
  handleView,
  columns,
  dense,
  activeTab,
  onStatusChange,
  onCreateRdvSemaine,
  onScheduleRdv,
  onMarkAsAbsent,
  onReplanifyRdv,
  onSendForm,
  useBackend = false,
}: CandidatureTableRowProps) {
  const [formModalOpen, setFormModalOpen] = useState(false);
  const [emailModalOpen, setEmailModalOpen] = useState(false);
  const [scheduleRdvModalOpen, setScheduleRdvModalOpen] = useState(false);
  const [rdvDate, setRdvDate] = useState(row.dateHeureRdvAgence || '');
  const [rdvDateDayjs, setRdvDateDayjs] = useState(() => {
    if (row.dateHeureRdvAgence) {
      try {
        const parsedDate = dayjs(row.dateHeureRdvAgence);
        return (parsedDate && parsedDate.isValid()) ? parsedDate : null;
      } catch (error) {
        console.warn('Invalid date format:', row.dateHeureRdvAgence);
        return null;
      }
    }
    return null;
  });
  const [hasDateChanged, setHasDateChanged] = useState(false);
  const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);
  const [contractStatus, setContractStatus] = useState(row.contrat || 'non signé');
  const [error, setError] = useState<string | null>(null);
  const theme = useTheme();

  const STATUS_OPTIONS = row.statut === CandidatureStatut.ATraiter
    ? [
      { value: CandidatureStatut.EnCours, label: 'En cours' },
      { value: CandidatureStatut.Retenu, label: 'Retenu' },
      { value: CandidatureStatut.Refuse, label: 'Refusé' },
      { value: CandidatureStatut.Blackliste, label: 'Blacklisté' },
    ]
    : [
      { value: CandidatureStatut.ATraiter, label: 'À traiter' },
      { value: CandidatureStatut.EnCours, label: 'En cours' },
      { value: CandidatureStatut.Retenu, label: 'Retenu' },
      { value: CandidatureStatut.Valide, label: 'Validé' },
      { value: CandidatureStatut.Refuse, label: 'Refusé' },
      { value: CandidatureStatut.Blackliste, label: 'Blacklisté' },
      { value: CandidatureStatut.Absent, label: 'Absent' },
      { value: CandidatureStatut.Replanifiee, label: 'Replanifiée' },
    ];
  const CONTRACT_OPTIONS = [
    { label: 'Signé', value: CandidatureContratStatut.Signe },
    { label: 'Non signé', value: CandidatureContratStatut.NonSigne }
  ];

  const hasRdvThisWeek = React.useMemo(() => {
    if (!row.dateHeureRdvAgence) return false;

    const today = new Date();

    const startOfWeek = new Date(today);
    startOfWeek.setDate(today.getDate() - today.getDay());
    startOfWeek.setHours(0, 0, 0, 0);

    const endOfPeriod = new Date(startOfWeek);
    endOfPeriod.setDate(startOfWeek.getDate() + 28);
    endOfPeriod.setHours(23, 59, 59, 999);

    const rdvDate = new Date(row.dateHeureRdvAgence);

    return rdvDate >= startOfWeek && rdvDate <= endOfPeriod;
  }, [row.dateHeureRdvAgence, row.nom, row.prenom]);

  const hasRdvScheduled = React.useMemo(() => {
    return !!row.dateHeureRdvAgence;
  }, [row.dateHeureRdvAgence]);

  const hasRdvForRetenus = React.useMemo(() => {
    if (activeTab !== CandidatureTab.Retenus) return false;
    return hasRdvScheduled;
  }, [activeTab, hasRdvScheduled]);

  const showRdvButton = (activeTab === CandidatureTab.Retenus || activeTab === CandidatureTab.RdvSemaine) && (onCreateRdvSemaine || (useBackend && onScheduleRdv));

  const getStatusColor = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return 'warning';
      case CandidatureStatut.EnCours:
        return 'info';
      case CandidatureStatut.Retenu:
        return 'primary';
      case CandidatureStatut.Valide:
        return 'success';
      case CandidatureStatut.Refuse:
        return 'error';
      case CandidatureStatut.Blackliste:
        return 'error';
      case CandidatureStatut.Absent:
        return 'default';
      default:
        return 'default';
    }
  };

  const getStatusHexColor = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return '#746CD4';
      case CandidatureStatut.EnCours:
        return '#0288d1';
      case CandidatureStatut.Retenu:
        return '#B78103';
      case CandidatureStatut.Valide:
        return '#36B37E';
      case CandidatureStatut.Refuse:
        return '#d32f2f';
      case CandidatureStatut.Blackliste:
        return '#2D2D2D';
      case CandidatureStatut.Absent:
        return '#757575';
      default:
        return '#757575';
    }
  };

  const getStatusLabel = (status: CandidatureStatut) => {
    switch (status) {
      case CandidatureStatut.ATraiter:
        return 'À traiter';
      case CandidatureStatut.EnCours:
        return 'En cours';
      case CandidatureStatut.Retenu:
        return 'Retenu';
      case CandidatureStatut.Valide:
        return 'Validé';
      case CandidatureStatut.Refuse:
        return 'Refusé';
      case CandidatureStatut.Blackliste:
        return 'Blacklisté';
      case CandidatureStatut.Absent:
        return 'Absent';
      default:
        return status;
    }
  };

  const handleRdvDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    const originalDate = row.dateHeureRdvAgence || '';
    const hasChanged = newValue !== originalDate;
    setHasDateChanged(hasChanged);
    setRdvDate(newValue);
  };

  const handleDatePickerChange = (newValue: dayjs.Dayjs | null) => {
    if (newValue && dayjs.isDayjs(newValue) && newValue.isValid()) {
      let adjustedDate = newValue;
 
      if (adjustedDate.hour() === 0 && adjustedDate.minute() === 0) {
        adjustedDate = adjustedDate.hour(9).minute(0);
      } else if (adjustedDate.hour() < 8) {
        adjustedDate = adjustedDate.hour(8).minute(0);
      } else if (adjustedDate.hour() > 18) {
        adjustedDate = adjustedDate.hour(18).minute(0);
      }
 
      const formattedDate = adjustedDate.format('YYYY-MM-DDTHH:mm:ss');
    
      const originalDate = row.dateHeureRdvAgence || '';
      const hasChanged = formattedDate !== originalDate;
      setHasDateChanged(hasChanged);
      
      setRdvDate(formattedDate);
      setRdvDateDayjs(adjustedDate);
    } else {
      // Check if clearing the date is different from original
      const originalDate = row.dateHeureRdvAgence || '';
      const hasChanged = '' !== originalDate;
      setHasDateChanged(hasChanged);
      
      setRdvDate('');
      setRdvDateDayjs(null);
    }
  };

  const formatDisplayValue = (value: dayjs.Dayjs | null) => {
    if (!value) return '';
    return value.format('DD/MM/YYYY HH:mm');
  };

  const handleClearDate = () => {
    setRdvDate('');
    setRdvDateDayjs(null);
    setHasDateChanged(false);
  };

  const handleReplanifyRdv = async () => {
    if (rdvDate && rdvDateDayjs && rdvDateDayjs.isValid()) {
      const validDate = dayjs(rdvDate);
      if (!validDate.isValid()) {
        setError('Date invalide. Veuillez sélectionner une date valide.');
        return;
      }

      if (useBackend && onReplanifyRdv) {
        try {
          const localDateTime = rdvDateDayjs.format('YYYY-MM-DDTHH:mm:ss');
          await onReplanifyRdv(row.id, localDateTime);
      
          setHasDateChanged(false);
        } catch (error) {
          setError('Erreur lors de la replanification du RDV');
        }
      } else {
        const updatedCandidature = {
          ...row,
          dateHeureRdvAgence: rdvDate,
          statut: CandidatureStatut.Retenu,
          wasAbsentBefore: true,
        };
        handleEdit(updatedCandidature);
      
        setHasDateChanged(false);
      }
    } else {
      setError('Veuillez sélectionner une date et heure valides.');
    }
  };

  const handleStatusChangeClick = (newStatus: CandidatureStatut) => {
    setIsStatusDialogOpen(true);
  };

  const handleStatusConfirm = (newStatus: CandidatureStatut, reason?: string) => {
    onStatusChange(row, newStatus, 'statut');
    setIsStatusDialogOpen(false);
  };

  const handleSendEmail = (subject: string, message: string) => {
    const updatedCandidature = {
      ...row,
      lastEmailSent: subject,
      lastEmailSentDate: new Date().toISOString(),
      lastEmailMessage: message
    };

    handleEdit(updatedCandidature);
  };

  const handleSendFormFromModal = async (formulaireId: string, observation: string) => {
    if (useBackend && onSendForm) {
      try {
        await onSendForm(row.id, formulaireId, observation);
      } catch (error) {
        setError('Erreur lors de l\'envoi du formulaire');
      }
    } else {
      const updatedCandidature = {
        ...row,
        lastFormSent: formulaireId,
        lastFormSentDate: new Date().toISOString(),
        observationForm: observation
      };

      handleEdit(updatedCandidature);
    }
  };

  const handleContractStatusChange = (e: React.ChangeEvent<{ value: unknown }>) => {
    const newContractStatus = e.target.value as 'signé' | 'non signé';
    setContractStatus(newContractStatus);

    const updatedCandidature = {
      ...row,
      contrat: newContractStatus
    };

    handleEdit(updatedCandidature);
  };

  const handleDocumentDownload = () => {
  };

  const handleCreateRdvClick = (event: React.MouseEvent) => {
    event.stopPropagation();

    if (useBackend && onScheduleRdv) {
      setScheduleRdvModalOpen(true);
    } else if (onCreateRdvSemaine) {
      onCreateRdvSemaine(row);
    }
  };

  const handleScheduleRdv = async (candidateId: string, rdvDateTime: string) => {
    if (onScheduleRdv) {
      try {
        await onScheduleRdv(candidateId, rdvDateTime);
        setScheduleRdvModalOpen(false);
      } catch (error) {
        setError('Erreur lors de la programmation du RDV');
      }
    }
  };

  const handleMarkAbsent = async (event: React.MouseEvent) => {
    event.stopPropagation();
    if (onMarkAsAbsent && useBackend) {
      try {
        await onMarkAsAbsent(row.id);
      } catch (error) {
        setError('Erreur lors du marquage comme absent');
      }
    }
  };

  const statusOptions: StatusOption[] = [
    { value: CandidatureStatut.ATraiter, label: 'À traiter' },
    { value: CandidatureStatut.EnCours, label: 'En cours' },
    { value: CandidatureStatut.Retenu, label: 'Retenu' },
    { value: CandidatureStatut.Valide, label: 'Validé' },
    { value: CandidatureStatut.Refuse, label: 'Refusé' },
    { value: CandidatureStatut.Blackliste, label: 'Blacklisté' },
    { value: CandidatureStatut.Absent, label: 'Absent' }
  ];

  const renderCell = (column: TableColumn) => {
    const value = row[column.id as keyof ICandidature];

    const getDefaultRenderable = (val: any): React.ReactNode => {
      if (val === null || val === undefined) return '-';
      if (val instanceof File) return val.name;
      if (typeof val === 'object') return JSON.stringify(val);
      return String(val);
    };

    switch (column.id) {
      case 'nom':
        return (
          <Stack direction="row" alignItems="center" spacing={2}>
            <Typography variant="body2" noWrap>
              {row.nom} {row.prenom}
            </Typography>
          </Stack>
        );

      case 'type':
        return (
          <Typography variant="body2" noWrap>
            {row.type ? row.type.replace('Candidature ', '') : 'Chauffeur'}
          </Typography>
        );

      case 'codePostal':
        return (
          <Typography variant="body2" noWrap>
            {row.codePostal}
          </Typography>
        );

      case 'ville':
        return (
          <Typography variant="body2" noWrap>
            {row.ville}
          </Typography>
        );

      case 'age':
        return (
          <Typography variant="body2" noWrap>
            {row.age}
          </Typography>
        );

      case 'email':
        return (
          <Typography variant="body2" noWrap>
            {row.email}
          </Typography>
        );

      case 'email_pro':
        if (row.statut === CandidatureStatut.Valide && row.email_pro) {
          return (
            <Typography variant="body2" noWrap>
              {row.email_pro}
            </Typography>
          );
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

      case 'telephone':
        return (
          <Typography variant="body2" noWrap>
            {row.telephone}
          </Typography>
        );

      case 'statut':

        const isStatusDisabled = activeTab === CandidatureTab.RdvSemaine || activeTab === CandidatureTab.AbsentRdv;

        return (
          <StatusMenu
            value={(row.statusRDV === StatutRendezVous.Absent && activeTab === CandidatureTab.RdvSemaine) ? CandidatureStatut.Absent : 
                    (row.statusRDV === StatutRendezVous.Replanifiee && activeTab === CandidatureTab.RdvSemaine) ? CandidatureStatut.Replanifiee : row.statut}
            options={STATUS_OPTIONS}
            onChange={(newStatus) => onStatusChange(row, newStatus, 'statut' as keyof ICandidature)}
            chipComponent={(props) => <StyledChip status={props.value} {...props} />}
            disabled={isStatusDisabled}
          />
        );

      case 'dateHeureRdvAgence':
        if (activeTab === CandidatureTab.AbsentRdv) {
          return (
            <Stack direction="row" alignItems="center" spacing={1} sx={{ minWidth: 280 }}>
              <Stack direction="column" spacing={0.5}>
                <LocalizationProvider
                  dateAdapter={AdapterDayjs}
                  adapterLocale="fr"
                >
                  <DateTimePicker
                    label=""
                    value={rdvDateDayjs}
                    onChange={handleDatePickerChange}
                    format="DD/MM/YYYY HH:mm"
                    formatDensity="dense"
                    ampm={false}
                    readOnly={false}
                    views={['year', 'month', 'day', 'hours', 'minutes']}
                    openTo="day"
                    minTime={dayjs().hour(8).minute(0)}
                    maxTime={dayjs().hour(18).minute(0)}
                    shouldDisableTime={(value, view) => {
                      if (view === 'hours' && value && dayjs.isDayjs(value) && value.isValid()) {
                        const hour = value.hour();
                        return hour < 8 || hour > 18;
                      }
                      return false;
                    }}
                    slotProps={{
                      textField: {
                        size: 'small',
                        variant: 'outlined',
                        placeholder: 'jj/mm/aaaa hh:mm',
                        inputProps: {
                          inputMode: 'numeric',
                          pattern: '[0-9/:]*'
                        },
                        sx: {
                          width: 200,
                          '& .MuiInputBase-root': {
                            fontSize: '0.875rem',
                            backgroundColor: '#fafafa',
                            borderRadius: 1,
                          },
                          '& .MuiOutlinedInput-notchedOutline': {
                            borderColor: '#e0e0e0',
                          },
                          '&:hover .MuiOutlinedInput-notchedOutline': {
                            borderColor: '#1976d2',
                          },
                          '& .MuiInputBase-input': {
                            padding: '8px 12px',
                          }
                        }
                      },
                      field: {
                        readOnly: false,
                        clearable: true
                      },
                      actionBar: {
                        actions: ['clear', 'today', 'accept']
                      },
                      popper: {
                        placement: 'bottom-start',
                        sx: {
                          '& .MuiPaper-root': {
                            boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.1)',
                            borderRadius: 2,
                          }
                        }
                      },
                      openPickerButton: {
                        sx: {
                          color: '#1976d2',
                          '&:hover': {
                            backgroundColor: 'rgba(25, 118, 210, 0.04)',
                          }
                        }
                      }
                    }}
                  />
                </LocalizationProvider>

                {!rdvDate && (
                  <Typography
                    variant="caption"
                    sx={{
                      color: '#888',
                      fontSize: '0.7rem',
                      fontStyle: 'italic',
                      textAlign: 'center'
                    }}
                  >
                    Saisie directe possible • 8h-18h
                  </Typography>
                )}
              </Stack>

              <ConditionalComponent isValid={hasDateChanged}>
                <CustomTooltip arrow title="Confirmer la replanification">
                  <IconButton
                    color="success"
                    onClick={handleReplanifyRdv}
                    size="small"
                    sx={{
                      backgroundColor: '#e8f5e8',
                      '&:hover': {
                        backgroundColor: '#c8e6c9',
                      },
                      border: '1px solid #4caf50',
                      borderRadius: 1,
                      width: 32,
                      height: 32
                    }}
                  >
                    <FontAwesomeIcon icon={faCircleCheck} size="sm" />
                  </IconButton>
                </CustomTooltip>
              </ConditionalComponent>

            </Stack>
          );
        } else if (row.dateHeureRdvAgence) {
          const raw = row.dateHeureRdvAgence;
          const date = new Date(raw);
          const onlyDatePattern = /^\d{4}-\d{2}-\d{2}$/;
          const hasOnlyDate = onlyDatePattern.test(raw);

          if (hasOnlyDate) {
            return date.toLocaleDateString('fr-FR', {
              year: 'numeric',
              month: 'numeric',
              day: 'numeric',
            }) + ' 09:00';
          }
          return date.toLocaleString('fr-FR', {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
          });
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

      case 'contrat':
        if (row.statut === CandidatureStatut.Valide) {
          const isContractStatusDisabled = activeTab === CandidatureTab.RdvSemaine || activeTab === CandidatureTab.AbsentRdv;
          return (
            <StatusMenu
              value={row.contrat || 'non signé'}
              options={CONTRACT_OPTIONS}
              onChange={(newStatus) => onStatusChange(row, newStatus, 'contrat' as keyof ICandidature)}
              chipComponent={(props) => <StyledChip status={props.value} {...props} />}
              disabled={isContractStatusDisabled}
            />
          );
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );
      case 'document':
        return (
          <CustomTooltip arrow title="Télécharger les pièces jointes">
            <IconButton
              color="primary"
              onClick={handleDocumentDownload}
              size="small"
              sx={ActionsIconButton}
            >
              <FontAwesomeIcon icon={faFileLines} size="sm" />
            </IconButton>
          </CustomTooltip>
        );

      case 'raisonRefus':
        if (row.raisonRefus) {
          return (
            <Typography variant="body2" noWrap>
              {row.raisonRefus}
            </Typography>
          );
        }
        return (
          <Typography variant="body2" color="text.secondary">
            -
          </Typography>
        );

      default:
        return (
          <Typography variant="body2" noWrap>
            {getDefaultRenderable(value)}
          </Typography>
        );
    }
  };

  return (
    <>
      <ContratStyledRow hover onDoubleClick={() => handleView(row)} style={{ cursor: 'pointer' }}>

        {columns.map((column, index: number) => (
          <TableCell
            key={column.id}
            align={column.align || 'left'}
            sx={{
              whiteSpace: 'nowrap',
              py: column.id === 'statut' ? 0.2 : dense ? 1 : 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: getStatusHexColor(row.statut),
                }}
              />
            </ConditionalComponent>
            {renderCell(column)}
          </TableCell>
        ))}

        <TableCell>
          <Stack direction="row" spacing={1} justifyContent="center">
            <ConditionalComponent isValid={row.statut === CandidatureStatut.ATraiter}>
              <>
                <CustomTooltip arrow title="Envoyer un formulaire">
                  <IconButton
                    color="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      setFormModalOpen(true);
                    }}
                    size="small"
                    sx={ActionsIconButton}
                  >
                    <FontAwesomeIcon icon={faPlus} size="sm" />
                  </IconButton>
                </CustomTooltip>
                <CustomTooltip arrow title="Envoyer un email">
                  <IconButton
                    color="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      setEmailModalOpen(true);
                    }}
                    size="small"
                    sx={ActionsIconButton}
                  >
                    <FontAwesomeIcon icon={faEnvelope} size="sm" />
                  </IconButton>
                </CustomTooltip>
              </>
            </ConditionalComponent>

            <ConditionalComponent isValid={!!(activeTab === CandidatureTab.RdvSemaine && !hasRdvScheduled && (onCreateRdvSemaine || (useBackend && onScheduleRdv)))}>
              <CustomTooltip arrow title="Programmer un RDV">
                <IconButton
                  color="primary"
                  onClick={handleCreateRdvClick}
                  size="small"
                  sx={{
                    ...ActionsIconButton,
                    backgroundColor: 'primary.lighter',
                    color: 'primary.main',
                    border: '1px solid',
                    borderColor: 'primary.main',
                    '&:hover': {
                      backgroundColor: 'primary.main',
                      color: 'white',
                      borderColor: 'primary.main',
                      transform: 'scale(1.05)',
                    },
                    transition: 'all 0.2s ease-in-out'
                  }}
                >
                  <FontAwesomeIcon icon={faCalendarDays} size="sm" />
                </IconButton>
              </CustomTooltip>
            </ConditionalComponent>

            <ConditionalComponent isValid={!!(activeTab === CandidatureTab.Retenus && !hasRdvScheduled && (onCreateRdvSemaine || (useBackend && onScheduleRdv)))}>
              <CustomTooltip arrow title="Programmer un RDV">
                <IconButton
                  color="primary"
                  onClick={handleCreateRdvClick}
                  size="small"
                  sx={{
                    ...ActionsIconButton,
                    backgroundColor: 'primary.lighter',
                    color: 'primary.main',
                    border: '1px solid',
                    borderColor: 'primary.main',
                    '&:hover': {
                      backgroundColor: 'primary.main',
                      color: 'white',
                      borderColor: 'primary.main',
                      transform: 'scale(1.05)',
                    },
                    transition: 'all 0.2s ease-in-out'
                  }}
                >
                  <FontAwesomeIcon icon={faCalendarDays} size="sm" />
                </IconButton>
              </CustomTooltip>
            </ConditionalComponent>

            <ConditionalComponent isValid={!!(activeTab === CandidatureTab.Retenus && hasRdvScheduled)}>
              <Tooltip
                arrow
                title={
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>RDV déjà programmé</div>
                    <div style={{ fontSize: '0.8em', opacity: 0.8 }}>
                      {row.dateHeureRdvAgence ?
                        `Le ${new Date(row.dateHeureRdvAgence).toLocaleDateString('fr-FR')} à ${new Date(row.dateHeureRdvAgence).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}` :
                        'Date non spécifiée'
                      }
                    </div>
                  </div>
                }
              >
                <span>
                  <IconButton
                    disabled
                    size="small"
                    sx={{
                      ...ActionsIconButton,
                      backgroundColor: 'success.lighter',
                      color: 'success.main',
                      border: '2px solid',
                      borderColor: 'success.main',
                      '&:hover': {
                        backgroundColor: 'success.lighter',
                        transform: 'scale(1.05)',
                      },
                      transition: 'all 0.2s ease-in-out'
                    }}
                  >
                    <FontAwesomeIcon
                      icon={faCalendarDays}
                      size="sm"
                    />
                  </IconButton>
                </span>
              </Tooltip>
            </ConditionalComponent>


            <ConditionalComponent isValid={!!(activeTab === CandidatureTab.RdvSemaine && useBackend && onMarkAsAbsent)}>
              <CustomTooltip arrow title="Marquer comme absent au RDV">
                <IconButton
                  color="warning"
                  onClick={handleMarkAbsent}
                  size="small"
                  sx={{
                    ...ActionsIconButton,
                    backgroundColor: 'warning.lighter',
                    color: 'warning.main',
                    border: '1px solid',
                    borderColor: 'warning.main',
                    '&:hover': {
                      backgroundColor: 'warning.main',
                      color: 'white',
                      borderColor: 'warning.main',
                      transform: 'scale(1.05)',
                    },
                    transition: 'all 0.2s ease-in-out'
                  }}
                >
                  <FontAwesomeIcon icon={faUserClock} size="sm" />
                </IconButton>
              </CustomTooltip>
            </ConditionalComponent>


            <TableActionColumn
              handleEdit={() => {
                handleEdit(row);
              }}
              tooltipTitles={{
                edit: 'Modifier',
                duplicate: 'Dupliquer',
                active: 'Actif',
                inactive: 'Inactif'
              }}
            />
          </Stack>
        </TableCell>
      </ContratStyledRow>

      <SendFormModal
        open={formModalOpen}
        onClose={() => setFormModalOpen(false)}
        candidature={row}
        onSend={handleSendFormFromModal}
        useBackend={useBackend}
      />

      <SendEmailModal
        open={emailModalOpen}
        onClose={() => setEmailModalOpen(false)}
        candidature={row}
        onSend={handleSendEmail}
        useBackend={useBackend}
      />

      <StatusChangeDialog
        open={isStatusDialogOpen}
        currentStatus={row.statut}
        statusOptions={statusOptions}
        onClose={() => setIsStatusDialogOpen(false)}
        onConfirm={handleStatusConfirm}
      />

      <ScheduleRdvModal
        open={scheduleRdvModalOpen}
        onClose={() => setScheduleRdvModalOpen(false)}
        candidature={row}
        onSchedule={handleScheduleRdv}
        useBackend={useBackend}
      />
    </>
  );
}