import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { TableColumn } from '@/shared/types/common';
import { ContratStyledRow, getStatusColor } from '@/shared/sections/contract/styles';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { IconButton } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { ActionsIconButton } from '@/shared/theme/css';
import { faFileExport, faPrint } from '@fortawesome/free-solid-svg-icons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { AttendanceSheet, AttendanceSheetList, AttendanceSheetStatus } from '@/shared/types/attendance-sheet';
import { useTeamStore } from '@/shared/api/stores/teamStore';
import { useAttendanceSheetStore } from '@/shared/api/stores/attendanceSheetStore';
import { enqueueSnackbar } from 'notistack';
import { getMonthLabel } from '../utils/attendance-utils';

type Props = {
  row: AttendanceSheet;
  columns: TableColumn[];
  refreshData: () => void;
  handleDetailsAttendance: (row: AttendanceSheet) => void; 
};
const TOOLTIP_TITLES = {
  imprimer: 'imprimer feuille de Présence',
  export: 'exporter feuille de Présence',
  active: 'feuille de Présence actif',
  inactive: 'feuille de Présence inactif',
}

export default function AttendanceTableRow({
  row,
  columns,
  refreshData,
  handleDetailsAttendance
}: Props) {
  const theme = useTheme();
 const {toggleAttendanceSheetStatus,exportAttendanceSheetPdf}=useAttendanceSheetStore();

const renderCellContent = (columnId: string, value: any) => {
  switch (columnId) {
    case "month":
      return getMonthLabel(value);
    default:
      return value;
  }
};
 const handleToggleActivation = async (isActive: boolean) => {
    try {
      await toggleAttendanceSheetStatus(row.id);
      refreshData();
      enqueueSnackbar('Statut modifié avec succès', { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Erreur lors du changement de statut', {
        variant: 'error'
      });
    }
  };
  const handleExportPdf = async () => {
  try {
    const monthNumber = typeof row.month === "string" && row.month.includes("-")
      ? parseInt(row.month.split("-")[0].trim())
      : Number(row.month);

    await exportAttendanceSheetPdf(
      Number(row.id),
      monthNumber,
      row.year
    );
    
    enqueueSnackbar('Export PDF généré avec succès', { variant: 'success' });
  } catch (error) {
    console.error('Erreur lors de l\'export PDF:', error);
    enqueueSnackbar('Erreur lors de l\'export PDF', { variant: 'error' });
  }
};
  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}  >

      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetailsAttendance(row)} 
            key={column.id}
            align={column.align }  
            sx={{ whiteSpace: 'nowrap', py: column.id === 'status' ? 0 : 'inherit', ...(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: getStatusColor(row.number),
              }}
            />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof AttendanceSheet])}
          </TableCell>
        ))}

      <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
      <div style={{ display: 'flex',justifyContent:'left', alignItems: 'center', gap: '8px' }}>
      <CustomTooltip title={TOOLTIP_TITLES.imprimer} arrow>
          <IconButton onClick={()=> void 0} size="small" sx={ActionsIconButton}>
            <FontAwesome icon={faPrint} width={16} />
          </IconButton>
        </CustomTooltip>
        <CustomTooltip title={TOOLTIP_TITLES.export} arrow>
          <IconButton onClick={handleExportPdf} size="small" sx={ActionsIconButton}>
            <FontAwesome icon={faFileExport} width={16} />
          </IconButton>
        </CustomTooltip>
        <TableActionColumn
             onToggle={(checked) => handleToggleActivation(checked)}
          isActive={row.status === AttendanceSheetStatus.ACTIVE}
          tooltipTitles={TOOLTIP_TITLES}
        />
      </div>
      </TableCell>
    </ContratStyledRow>
  );
}

