import React, { useState } from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { format } from 'date-fns';
import { useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { ContratStyledRow, getStatusColor, StatusChip } from '../../contract/styles';
import { Circuit, CircuitState, circuitStateOptions, ICircuit } from '@/shared/types/circuit';
import { _CIRCUIT_STATUS, getEtatLabel } from '@/shared/_mock/_circuit';
import { AntSwitch } from '@/shared/components/table/styles';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { TableColumn } from '@/shared/types/common';
import { dateFormat, formatDate } from '@/utils/format-time';
import { getEtatColor } from '../utils/form-fields-circuit';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { _CONTRACT_STATUS } from '@/shared/_mock/_Contrat';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import { enqueueSnackbar } from 'notistack';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { PassengerCircuitStatusChip } from '@/shared/theme/css';

type Props = {
  handleDetailsContract: (contrat: Circuit) => void;
  row: Circuit;
  dense: boolean;
  columns: TableColumn[];
};

export default function CircuitTableRow({
  dense,
  row,
  handleDetailsContract,
  columns,
}: Props) {
  const { toggleActive, updateCircuitStatus } = useCircuitStore();
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const handleToggleActivation = async () => {
    try {
      await toggleActive(row.id);
      enqueueSnackbar("Modification de l'état du circuit réussie", { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la modification de l'état du circuit", { variant: 'error' });
    }
  }

  const handleToggleActivationClick = () => {
    setShowConfirmDialog(true);
  };

  const handleConfirmToggle = () => {
    setShowConfirmDialog(false);
    handleToggleActivation();
  };

  const handleCancelToggle = () => {
    setShowConfirmDialog(false);
  };

  const handleStatusChange = async (newStatus: string) => {
    try {
      await updateCircuitStatus(row.id, newStatus as CircuitState);
      enqueueSnackbar("Statut du circuit mis à jour avec succès", { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la mise à jour du statut", { variant: 'error' });
    }
  };
  const theme = useTheme();

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'startDate':
      case 'lastAmendmentDate':
      case 'endDate':
      case 'createdAt':
        return formatDate(value,dateFormat.isoDate);
      case 'circuitState':
        return (
          <StatusMenu
            value={value}
            options={circuitStateOptions}
            onChange={(newStatus) => handleStatusChange(newStatus as CircuitState)}
            chipComponent={PassengerCircuitStatusChip}
          />
        );
      case 'lotNames':
        return row.lotNames ? row.lotNames.join(', ') : '-';
      default:
        return value;
    }
  };

  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}>
      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetailsContract(row)}
            key={column.id}
            align={column.align || 'left'}
            sx={{ whiteSpace: 'nowrap', py: column.id === 'etat' ? 0.2 : dense ? 1 : 2, ...(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: row.colorCode || getEtatColor(row.circuitState),
              }}
            />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof Circuit])}
          </TableCell>
        ))}
      <TableCell
        align="center"
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <CustomTooltip title={row.active ? 'Circuit actif' : 'Circuit inactif'} arrow>
          <AntSwitch
            theme={theme}
            checked={row.active}
            onChange={() => handleToggleActivationClick()}
            size="small"
          />
        </CustomTooltip>
      </TableCell>
      <ConfirmDialog
        open={showConfirmDialog}
        title="Confirmer le changement d'état"
        content={`Êtes-vous sûr de vouloir ${row.active ? 'activer' : 'désactiver'} ce circuit ?`}
        onConfirm={handleConfirmToggle}
        onCancel={handleCancelToggle}
        confirmButtonText="Confirmer"
        cancelButtonText="Annuler"
        confirmButtonColor="warning"
      />
    </ContratStyledRow>
  );
}
