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 { ILeave } from '@/shared/types/leave';
import StatusSelect from '@/shared/components/dialog/statusSelect';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

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: ILeave) => void;
  handleDetails: (conge: ILeave) => void;
  selected: boolean;
  handleViewHistory: (conge: ILeave) => void;
  row: ILeave;
  dense: boolean;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
};

export default function CongeTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  selected,
  onSelectRow,
  handleViewHistory,
  columns,
}: Props) {
  const theme = useTheme();
  const [openHistorique, setOpenHistorique] = useState(false);
 
  const handleHistoryClick = () => {
    setOpenHistorique(true);
  };

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

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateSubmission':
      case 'dateDebut':
      case 'dateFin':
      case 'dateTraitement':
        return value ? formatDate(value, dateFormat.isoDate) : '-';
      
      case 'status':
        return (
          <StatusSelect
            value={value}
            options={LEAVE_STATUS}
            onChange={handleStatusChange}
            chipComponent={StatusChip}
            fullWidth
          />
        );
  
      case 'modeReception':
        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 ILeave])}
            </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>

      <HistoriqueDialog
        open={openHistorique}
        onClose={() => setOpenHistorique(false)}
        historique={row.history}
      />
    </>
  );
}