import React, { useState } from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { alpha, useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { TableColumn } from '@/shared/types/common';
import { dateFormat, formatDate } from '@/utils/format-time';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHistory } from '@fortawesome/free-solid-svg-icons';
import TableActionColumn from '@/shared/components/table/table-action-column';
import HistoriqueDialog from '../components/historique-dialog-conge';
import { CongeStyledRow } from '../styles';
import { getStatusColor, StatusChip } from '../../styles';
import { IDemandeAbsence } from '@/shared/types/leave';
import StatusSelect from '@/shared/components/dialog/statusSelect';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';
import { ILeaveHistory } from '@/shared/types/leave';

const STATUS_LABELS = {
  en_attente: 'En attente',
  approuve: 'Approuvée',
  refuse: 'Refusée',
} as const;

const LEAVE_STATUS = [
  { 
    value: 'En attente', 
    label: 'En attente',
    color: (theme: any) => theme.palette.primary.main,
    backgroundColor: (theme: any) => alpha(theme.palette.primary.main, 0.1)
  },
  { 
    value: 'Approuvée', 
    label: 'Approuvée',
    color: '#36B37E',
    backgroundColor: '#E9FBF0'
  },
  { 
    value: 'Refusée', 
    label: 'Refusée',
    color: '#FF3434',
    backgroundColor: '#FFE1E1'
  },
];

const TOOLTIP_TITLES = {
  edit: "Modifier congé",
  active: "Congé actif",
  inactive: "Congé inactif",
};

type Props = {
  handleEdit: (conge: IDemandeAbsence) => void;
  handleDetails: (conge: IDemandeAbsence) => void;
  selected: boolean;
  handleViewHistory: (conge: IDemandeAbsence) => void;
  row: IDemandeAbsence;
  dense: boolean;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
};

export default function CongeTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  selected,
  onSelectRow,
  handleViewHistory,
  columns,
}: Props) {
  const theme = useTheme();
  const [historique, setHistorique] = useState<ILeaveHistory[]>([]);
  const { getLeaveHistory } = useAbsenceStoree();
 
  const handleHistoryClick = async () => {
    try {
      console.log('Clicking history button for row:', row.id);
      const result = await getLeaveHistory(row.id);
      console.log('History data received:', result);
      
      if (result.success) {
        handleViewHistory(row); // Call parent handler to show dialog
      }
    } catch (error) {
      console.error('Failed to fetch history:', error);
    }
  };

  const handleStatusChange = (newStatus: string) => {
    // Implémentation du changement de statut
    console.log('Nouveau statut:', newStatus);
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'submissionDate':
      case 'startDate':
      case 'endDate':
      case 'processDate':
        return value ? formatDate(value, dateFormat.isoDate) : '-';
      
      case 'status':
        return (
          <StatusSelect
            value={value}
            options={LEAVE_STATUS}
            onChange={handleStatusChange}
            chipComponent={StatusChip}
            fullWidth
          />
        );
  
      case 'leaveType':
        // Map backend enum to display label
        switch(value) {
          case 'LEAVE_SICK': return 'Congé maladie';
          case 'LEAVE_PARENTAL': return 'Congé parental';
          case 'LEAVE_PAID': return 'Congé annuel';
          case 'LEAVE_UNPAID': return 'Congé sans solde';
          case 'LEAVE_RTT': return 'RTT';
          default: return value || '-';
        }

      case 'notificationMode':
        // Map NotificationMode values to display labels
        switch(value) {
          case 'SMS': return 'SMS';
          case 'Email': return 'Email';
          case 'Application': return 'Application';
          default: return value || '-';
        }

      case 'employeeName':
        return value || '-';
      
      default:
        return value || '-';
    }
  };

  return (
    <CongeStyledRow 
      hover 
      style={{ cursor: 'pointer' }}
    >
      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetails(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.status),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IDemandeAbsence])}
          </TableCell>
        ))}

      <TableCell 
        align="right" 
        sx={{ px: 1, whiteSpace: 'nowrap' }}
        onClick={(e) => e.stopPropagation()}
      >
        <TableActionColumn
          handleEdit={() => handleEdit(row)}
          onToggle={(checked) => console.log('Toggle:', checked)}
          isActive={row.isActive}
          tooltipTitles={TOOLTIP_TITLES}
          additionalActions={[
            {
              icon: <FontAwesomeIcon icon={faHistory} size="sm" />,
              tooltip: "Voir l'historique",
              onClick: handleHistoryClick
            }
          ]}
        />
      </TableCell>
    </CongeStyledRow>
  );
}