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 { CircularProgress, 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, printAttendanceSheetPdf, printingId, exportingId } = useAttendanceSheetStore();
  const isCurrentRowPrinting = printingId === Number(row.id);
  const isCurrentRowExporting = exportingId === Number(row.id);
  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' });
    }
  };
  const handlePrintPdf = async () => {
    try {
      const monthNumber = typeof row.month === "string" && row.month.includes("-")
        ? parseInt(row.month.split("-")[0].trim())
        : Number(row.month);

      await printAttendanceSheetPdf(
        Number(row.id),
        monthNumber,
        row.year
      );

      enqueueSnackbar('Impression en cours...', { variant: 'info' });
    } catch (error) {
      console.error('Erreur lors de l\'impression PDF:', error);
      enqueueSnackbar('Erreur lors de l\'impression 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={isCurrentRowPrinting ? 'Impression en cours...' : TOOLTIP_TITLES.imprimer} arrow>
            <IconButton
              onClick={handlePrintPdf}
              size="small"
              sx={ActionsIconButton}
              disabled={isCurrentRowPrinting || Boolean(printingId)}
            >
              <ConditionalComponent
                isValid={isCurrentRowPrinting}
                defaultComponent={<FontAwesome icon={faPrint} width={16} />}
              >
                <CircularProgress size={16} color="inherit" />
              </ConditionalComponent>
            </IconButton>
          </CustomTooltip>

          <CustomTooltip title={isCurrentRowExporting ? 'Export en cours...' : TOOLTIP_TITLES.export} arrow>
            <IconButton
              onClick={handleExportPdf}
              size="small"
              sx={ActionsIconButton}
              disabled={isCurrentRowExporting || Boolean(exportingId)}
            >
              <ConditionalComponent
                isValid={isCurrentRowExporting}
                defaultComponent={<FontAwesome icon={faFileExport} width={16} />}
              >
                <CircularProgress size={16} color="inherit" />
              </ConditionalComponent>
            </IconButton>
          </CustomTooltip>
          <TableActionColumn
            onToggle={(checked) => handleToggleActivation(checked)}
            isActive={row.status === AttendanceSheetStatus.ACTIVE}
            tooltipTitles={TOOLTIP_TITLES}
          />
        </div>
      </TableCell>
    </ContratStyledRow>
  );
}

