import React, { useEffect, useState } from 'react';
import TableCell from '@mui/material/TableCell';
import SvgColor from '@/shared/components/svg-color';
import { TableColumn } from '@/shared/types/common';
import { dateFormat, formatDate } from '@/utils/format-time';
import { ContratStyledRow, getStatusColor, StatusChip } from '../../contract/styles';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { _CIRCUIT_STATUS } from '@/shared/_mock/_circuit';
import StatusMenu from '@/shared/components/table/StatusMenu';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { _PassengerStatus, IPassengerList, State } from '@/shared/types/passenger';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { PassengerCircuitStatusChip } from '@/shared/theme/css';
import { getLabel } from '@/shared/_mock';
import { _classesOptions, _RELATION_TYPE_OPTIONS } from '../utils/form-fields-usager';
import { enqueueSnackbar } from 'notistack';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';

type Props = {
  handleEdit: (usager: IPassengerList) => void;
  handleDetails: (usager: IPassengerList) => void;
  handleCopy: (usager: IPassengerList) => void;
  row: IPassengerList;
  dense: boolean;
  columns: TableColumn[];
  onStatusChange: (row: IPassengerList, newStatus: string, field: keyof IPassengerList) => void;  
};
const TOOLTIP_TITLES = {
  edit: 'Modifier usager',
  duplicate:"Copier usager",
  active:"usager Actif",
  inactive:"usager Inactif",
};
export default function UsagerTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  handleCopy,
  columns,
  onStatusChange
}: Props) {
  const { toggleArchive, updatePassengerStatus } = usePassengerStore();
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [departmentColor, setDepartmentColor] = useState<string | null>(null);
  const { getDepartmentHexColorById } = useInfrastructureStore();

  useEffect(() => {
    const fetchDepartmentColor = async () => {
      const color = await getDepartmentHexColorById(row.idDepartment.toString());
      setDepartmentColor(color);
    };
    if (row.idDepartment) {
      fetchDepartmentColor();
    }
  }, [row.idDepartment, getDepartmentHexColorById]);

  const handleToggleActivation = async () => {
    try {
      await toggleArchive(row.id);
      enqueueSnackbar("Modification de l'état de l'usager réussie", { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la modification de l'état de l'usager", { variant: 'error' });
    }
  }

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

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

  const handleCancelToggle = () => {
    setShowConfirmDialog(false);
  };
  const handleStatusChange = async (newStatus: string) => {
    try {
      await updatePassengerStatus(row.id, newStatus as State);
      enqueueSnackbar("Statut de l'usager mis à jour avec succès", { variant: 'success' });
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de la mise à jour du statut", { variant: 'error' });
    }
  };
  const renderCellContent = (columnId: string, value: any) => {
    if (value === null) {
      return '-';
    }

    switch (columnId) {
      case 'landlinePhoneNumbers':
        return row.representatives?.length ? row.representatives[0]?.contacts[0]?.landlinePhoneNumbers : '-';
      case 'mobilePhoneNumbers':
        return row.representatives?.length ? row.representatives[0]?.contacts[0]?.mobilePhoneNumbers : '-';
      case 'code':
        return row.representatives?.length ? row.representatives[0]?.circuitCode : '-';
      case 'address':
        return row.representatives?.length ? row.representatives[0]?.addresses[0]?.additionalAddress : '-';
      case 'type':
        return  row.representatives[0]?.type ? getLabel(row.representatives[0]?.type, _RELATION_TYPE_OPTIONS) : '-';
      case 'establishmentName':
        return  row.establishmentTransportSchedules.length ? row.establishmentTransportSchedules[0]?.establishmentName : '-';
      case 'schoolClass':
        return  getLabel(value,_classesOptions);
      case 'birthDate':
      case 'startTransport':
      case 'lastAmendmentDate':
      case 'createdAt':
        return formatDate(value, dateFormat.isoDate);
      case 'state':
        return (
          <StatusMenu
            value={value}
            options={_PassengerStatus}
            onChange={(newStatus) => handleStatusChange(newStatus as State)}
            chipComponent={PassengerCircuitStatusChip}
          />              
        );
      default:
        return value;
    }
  };

  return (
    <ContratStyledRow 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 === 'etat' ? 0.2 : dense ? 0 : 1, ...(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: departmentColor ?? '#ccc',
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IPassengerList])}
          </TableCell>
        ))}
      <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <TableActionColumn
          handleEdit={() => handleEdit(row)}
          onDuplicate={() => handleCopy(row)}
          onToggle={() => handleToggleActivationClick()}
          isActive={row.archived}
          tooltipTitles={TOOLTIP_TITLES}
          isBackendProcessing={true}
        />
      </TableCell>
      <ConfirmDialog
        open={showConfirmDialog}
        title="Confirmer le changement d'état"
        content={`Êtes-vous sûr de vouloir ${row.archived ? 'activer' : 'désactiver'} cet usager ?`}
        onConfirm={handleConfirmToggle}
        onCancel={handleCancelToggle}
        confirmButtonText="Confirmer"
        cancelButtonText="Annuler"
        confirmButtonColor="warning"
      />
    </ContratStyledRow>
  );
}
