import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { dateFormat, formatDate } from '@/utils/format-time';
import { RHAbsenceTableRowProps, IRHAbsence } from '../../../../types/absence-rh';
import { ContratStyledRow, getStatusColor, StatusChip } from '@/shared/sections/contract/styles';
import { getAbsenceEtat, getRHAbsenceStatut, RH_ABSENCE_STATUS_OPTIONS, getStatusChipStatus, getAbsenceTypeLabel } from '@/shared/_mock/_rhAbsence';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FontAwesome from '@/shared/components/fontawesome';
import { faPenToSquare, faFileAlt } from '@fortawesome/free-solid-svg-icons';
import { ActionsIconButton } from '@/shared/theme/css';
import { IconButton } from '@mui/material';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { faCircleCheck } from '@fortawesome/free-regular-svg-icons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { DriverAbsenceStatus } from '@/shared/types/driver-absence';
import { getLabel } from '@/shared/_mock';
import { _OPTION_DRIVER_ABSENCE } from '@/shared/_mock/_absenceDriver';

// Define status color mapping
const STATUS_COLORS: {
  [key: string]: { color: string; backgroundColor: string };
} = {
  'En cours': {
    color: '#36B37E',
    backgroundColor: '#E9FBF0',
  },
  'Non traité': {
    color: '#FF3434',
    backgroundColor: '#FFE1E1',
  },
  'Traité': {
    color: '#36B37E',
    backgroundColor: '#E9FBF0',
  },
  'Waiting': {
    color: '#FF3434',
    backgroundColor: '#FFE1E1',
  },
  'Unprocessed': {
    color: '#FF3434',
    backgroundColor: '#FFE1E1',
  },
  'In_progress': {
    color: '#FF9500',
    backgroundColor: '#FFF4E6',
  },
  'Approved': {
    color: '#36B37E',
    backgroundColor: '#E9FBF0',
  },
  'Rejected': {
    color: '#FF3434',
    backgroundColor: '#FFE1E1',
  },
};

export default function AbsenceTableRow({
  row,
  dense,
  handleEdit,
  handleDetails,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
  isTraiteTable
}: RHAbsenceTableRowProps<IRHAbsence>) {
  const theme = useTheme();
  const handleStatusChange = (row: IRHAbsence, newStatus: string, field: keyof IRHAbsence) => {
    if (onStatusChange) {
      onStatusChange(row, newStatus, field);
    }
  };

  const handleExportDocument = (event: React.MouseEvent, row: IRHAbsence) => {
    event.stopPropagation();
    
    const fileUrl = row.justificationFileUrl;
    
    if (!fileUrl) {
      console.warn('No justification file URL found for absence:', row.id);
      return;
    }

    try {
      // Open the file in a new tab/window
      window.open(fileUrl, '_blank', 'noopener,noreferrer');
    } catch (error) {
      console.error('Error opening justification file:', error);
      
      // Fallback: try to download the file
      try {
        const link = document.createElement('a');
        link.href = fileUrl;
        link.download = `justificatif_absence_${row.id}`;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (downloadError) {
        console.error('Error downloading justification file:', downloadError);
      }
    }
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateDebut':
      case 'dateFin':
      case 'previentLe':
      case 'startDate':
      case 'endDate':
      case 'submittedAt':
      case 'processedAt':
        return value ? formatDate(value, dateFormat.isoDate) : '-';
      case 'nbrHeures':
      case 'hoursCount':
        return value !== undefined ? `${value}h` : '-';
      case 'validerPar':
      case 'autorisePar':
      case 'departement':
      case 'validatedBy':
      case 'authorizedBy':
        return value || '-';
      case 'typeAbsenceLabel':
        // Only handle ABSENCE types since RH interface only shows absences
        if (row.absenceType) {
          return getAbsenceTypeLabel(row.absenceType, 'ABSENCE');
        }
        return '-';
      case 'typeAbsence':
        // Display the raw absence type
        return row.absenceType || value || '-';
      case 'nomChauffeur':
        // Handle user name display
        if (row.user) {
          return `${row.user.firstName} ${row.user.lastName}`;
        }
        return value || 'Utilisateur inconnu';
      case 'numeroEnregistrement':
        // Format the absence number
        return `ABS-${String(row.id).padStart(4, '0')}`;
      case 'type':
        // Display function type in French
        if (row.user?.functionType === 'DRIVER') {
          return 'Chauffeur';
        } else if (row.user?.functionType === 'SEDENTARY') {
          return 'Sédentaire';
        }
        return value || '-';
      case 'modeReception':
      case 'receivingMethod':
        // Map receiving method to French
        const receivingMethodMap: { [key: string]: string } = {
          'APPLICATION': 'Application',
          'EMAIL': 'Email',
          'PHONE': 'Téléphone',
          'PORTAL': 'Portail'
        };
        return receivingMethodMap[value] || value || '-';
      case 'statut':
      case 'state':
        // Custom chip component that maps backend status to StatusChip status
        const RHStatusChip = (props: any) => (
          <StatusChip 
            {...props}
            status={getStatusChipStatus(props.status)} // Map backend status to chip status
            theme={theme}
          />
        );

        return (
          <StatusMenu
            value={value}
            options={RH_ABSENCE_STATUS_OPTIONS.map(opt => ({
              value: opt.value,
              label: opt.label
            }))}
            onChange={(newStatus) => handleStatusChange(row, newStatus, 'statut')}
            chipComponent={RHStatusChip}
            sx={{ width: '130px' }}
          />
        );
      case 'justificatif':
      case 'justificationFileUrl':
        return (value || row.justificationFileUrl) ? (
          <CustomTooltip title="Voir le justificatif" arrow>
            <IconButton
              onClick={(e) => handleExportDocument(e, row)}
              size="small"
              sx={{
                ...ActionsIconButton,
                color: '#36B37E',
                backgroundColor: '#E9FBF0',
                '&:hover': {
                  backgroundColor: '#D3F3E8',
                },
              }}
            >
              <FontAwesome icon={faFileAlt} width={16} />
            </IconButton>
          </CustomTooltip>
        ) : (
          <span style={{ 
            color: '#999999',
            fontSize: '0.875rem',
            fontStyle: 'italic' 
          }}>
            Aucun
          </span>
        );
      case 'affecteTrajet':
      case 'affectedToTrip':
        const isAffected =
          typeof value === 'boolean' ? value :
            typeof value === 'string' ? value.toLowerCase() === 'oui' :
              row.affectedToTrip || false;

        return (
          <StatusChip
            label={isAffected ? 'Oui' : 'Non'}
            status={isAffected ? 'Oui' : 'Non'}
            theme={theme}
            size="small"
            sx={{
              color: isAffected ? '#36B37E' : '#FF3434',
              backgroundColor: isAffected ? '#E9FBF0' : '#FFE1E1',
            }}
          />
        );
      case 'numberOfDays':
      case 'daysCount':
        return `${value || 0} jour${(value || 0) > 1 ? 's' : ''}`;
      default:
        return value || '-';
    }
  };

  return (
    <ContratStyledRow hover
      style={{ cursor: 'pointer' }}>
      {columns
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetails(row)}
            key={column.id}
            align={column.align}
            sx={{
              whiteSpace: 'nowrap',
              py: column.id === 'status' ? 0.2 : dense ? 0 : 1,
              ...(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: STATUS_COLORS[row.state || row.statut || '']?.color || getStatusColor(row.statut || ''),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IRHAbsence])}
          </TableCell>
        ))}
      {/* Actions column - always show for all tables */}
      <TableCell align="center" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <CustomTooltip title="Modifier l'absence" arrow>
          <IconButton onClick={() => handleEdit(row)} size="small" sx={ActionsIconButton}>
            <FontAwesome icon={faPenToSquare} width={16} />
          </IconButton>
        </CustomTooltip>
      </TableCell>
    </ContratStyledRow>
  );
} 