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 { AbsenceTableRowProps, IAbsence } from '@/shared/types/absence';
import { ContratStyledRow, getStatusColor, StatusChip } from '../../contract/styles';
import { _OPTION_DEMANDE } from '@/shared/sections/absence/utils/form-fields-absence';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import FontAwesome from '@/shared/components/fontawesome';
import { faPenToSquare, faTimes } from '@fortawesome/free-solid-svg-icons';
import { faCircleCheck} from '@fortawesome/free-regular-svg-icons';
import { ActionsIconButton } from '@/shared/theme/css';
import { IconButton } from '@mui/material';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { _SENS_AR } from '@/shared/_mock';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { alpha, styled } from '@mui/material/styles';
import { Chip } from '@mui/material';
import { AbsenceStatusChip, getAbsenceStatusColor } from '../utils/status-chip';
import { 
  UNPROCESSED_STATE_OPTIONS, 
  PROCESSED_STATE_OPTIONS,
  TRAJET_OPTIONS,
  mapStateToBackend,
  FRONTEND_STATES
} from '../utils/absence-constants';

const TrajetSelector = ({ value, onChange, row }: { value: string[], onChange: (row: IAbsence, newValues: string[]) => void, row: IAbsence }) => {
  const theme = useTheme();
  
  const values = Array.isArray(value) ? value : [value];
  
  const displayText = values.includes('aller') && values.includes('retour') 
    ? 'A/R'
    : values.join(', ');

  const handleStatusChange = (newValue: string) => {
    if (values.includes(newValue)) {
      const newValues = values.filter(v => v !== newValue);
      onChange(row, newValues.length ? newValues : values); 
    } else {
      const newValues = [...values, newValue];
      onChange(row, newValues);
    }
  };

  return (
    <StatusMenu
      value={displayText}
      options={TRAJET_OPTIONS}
      onChange={handleStatusChange}
      chipComponent={AbsenceStatusChip}
      sx={{width:"100px"}}
    />
  );
};

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

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'usager':
        if (value && typeof value === 'object' && 'label' in value) {
          return value.label;
        }
        return value;
      case 'dateDebut':
      case 'dateFin':
      case 'previentLe':
        return formatDate(value, dateFormat.isoDate);
      case 'sensAR':
        const values = Array.isArray(value) ? value : [value];
        const displayText = values.includes('aller') && values.includes('retour') 
          ? 'A/R' 
          : values.join(', ');
        
        const handleChange = (newValue: string) => {
          let updatedValues: string[];
          
          switch(newValue) {
            case 'A/R':
              updatedValues = ['aller', 'retour'];
              break;
            case 'aller':
            case 'retour':
              updatedValues = [newValue];
              break;
            default:
              return;
          }
          
          onConcernedTripChange?.(row, updatedValues);
        };
      
        return (
          <StatusMenu
            value={displayText}
            options={TRAJET_OPTIONS}
            onChange={handleChange}
            chipComponent={AbsenceStatusChip}
            sx={{width:"100px"}}
          />
        );
      case 'etat':
        const stateOptions = isTraiteTable ? PROCESSED_STATE_OPTIONS : UNPROCESSED_STATE_OPTIONS;
        return (
          <StatusMenu
            value={Array.isArray(value) ? value[0] : value}
            options={stateOptions}
            onChange={(newStatus) => {
              const updatedRow = {
                ...row,
                state: mapStateToBackend(newStatus)
              };
              onStatusChange?.(updatedRow, newStatus, "etat");
            }}
            chipComponent={AbsenceStatusChip}
            sx={{width:"130px"}}
          />
        );
      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: getAbsenceStatusColor(row.etat[0])
              }}
            />
          </ConditionalComponent>
          {renderCellContent(column.id, row[column.id as keyof IAbsence])}
        </TableCell>
      ))}
      <ConditionalComponent isValid={!isTraiteTable}>
        <TableCell align="center" sx={{ px: 1, whiteSpace: 'nowrap' }}>
          <CustomTooltip title="Valider l'absence" arrow>
            <IconButton onClick={() => {const updatedRow = {
              ...row,
              state:"Processed"
            };
            onStatusChange?.(updatedRow, 'Traité', 'etat');
            }} 
            size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faCircleCheck} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Modifier l'absence" arrow>
            <IconButton onClick={() => handleEdit(row)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faPenToSquare} width={16} />
            </IconButton>
          </CustomTooltip>
        </TableCell>
      </ConditionalComponent>
    </ContratStyledRow>
  );
}
