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 } 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',
  },
};

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();
    // Add your export document logic here
    console.log('Export document for:', row);
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateDebut':
      case 'dateFin':
      case 'previentLe':
        return formatDate(value, dateFormat.isoDate);
      case 'nbrHeures':
        return value !== undefined ? `${value}h` : '-';
      case 'validerPar':
      case 'autorisePar':
      case 'departement':
        return value || '-';
      case 'statut':
        return isTraiteTable ? (
          <StatusMenu
            value={value}
            options={_OPTION_DRIVER_ABSENCE}
            onChange={(newStatus) => handleStatusChange(row, newStatus, 'statut')}
            chipComponent={StatusChip}
            sx={{ width: '130px' }}
          />
        ) : (
          <StatusChip
            label={getLabel(value, _OPTION_DRIVER_ABSENCE)}
            status={value}
            theme={theme}
          />
        );
      case 'justificatif':
        return value ? (
          <CustomTooltip title="Exporter le justificatif" arrow>
            <IconButton
              onClick={(e) => handleExportDocument(e, row)}
              size="small"
              sx={ActionsIconButton}
            >
              <FontAwesome icon={faFileAlt} width={16} />
            </IconButton>
          </CustomTooltip>
        ) : null;
      case 'affecteTrajet':
        const isAffected =
          typeof value === 'boolean' ? value :
            typeof value === 'string' ? value.toLowerCase() === 'oui' :
              false;
        console.log(value);

        return (
          <StatusChip
            label={isAffected ? 'Oui' : 'Non'}
            status={isAffected ? 'Oui' : 'Non'}
            theme={theme}
            size="small"
            sx={{
              color: isAffected ? '#36B37E' : '#FF3434',
              backgroundColor: isAffected ? '#E9FBF0' : '#FFE1E1',
            }}
          />
        );
      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.statut]?.color || getStatusColor(row.statut),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IRHAbsence])}
          </TableCell>
        ))}
      {isTraiteTable ?
        <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>
  );
} 