import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { AddressDTO, CollaboratorStatus, IAgent, UserStatus } from '@/shared/types/client';
import TableActionColumn from '@/shared/components/table/table-action-column';
import SvgColor from '@/shared/components/svg-color';
import { TableRow } from '@mui/material';
import { TableColumn } from '@/shared/types/common';
import { dateFormat, formatDate } from '@/utils/format-time';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { AgentStyledRow, StatusChip, getStatusColor } from '../../styles';
import { _AGENT_STATUS } from '@/shared/_mock/_agent';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useCollaboratorStore } from '@/shared/api/stores/CollaboratorStore';
import SchedulePreview from './SchedulePreview';
import ScheduleSummary from './ScheduleSummary';

type Props = {
  handleEditAgent: (agent: IAgent) => void;
  handleDetailsAgent: (agent: IAgent) => void;
  handleCopyAgent: (agent: IAgent) => void;
  selected: boolean;
  row: IAgent;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
  onStatusChange: (row: IAgent, newStatus: string, field: keyof IAgent) => void;
};

const TOOLTIP_TITLES = {
  edit: 'Modifier agent',
  duplicate: 'Copier agent',
  active: 'Agent actif',
  inactive: 'Agent inactif',
};

export default function AgentTableRow({
  row,
  handleEditAgent,
  handleDetailsAgent,
  handleCopyAgent,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
}: Props) {
  const { toggleActiveStatus, changeStatus } = useCollaboratorStore();
  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'status':
        return (
          <StatusMenu
            value={row.collaboratorStatus}
            options={_AGENT_STATUS}
            onChange={async (newStatus) => {
              try {
                await changeStatus(row.id, newStatus as CollaboratorStatus);
                onStatusChange(row, newStatus, 'collaboratorStatus');
              } catch (error) {
                console.error('Erreur lors de la mise à jour du statut de collaboration', error);
              }
            }}
            chipComponent={StatusChip}
            sx={{ width: '120px' }}
          />
        );

      case 'role':
        return row.roles?.map((role) => role.name).join(', ') || '-';

      case 'address': {
        const address = row.addresses?.[0]?.additionalAddress ;
        return address || '-';
      }
      case 'schedule': {
        return <ScheduleSummary schedule={row.schedule} compact={true} />;
      }

      default:  
        return value;
    }
  };
  const handleStatusChange = async () => {
    try {
      await toggleActiveStatus(row.id);
    } catch (error) {
      console.error('Erreur lors du changement de statut du client', error);
    }
  };

  return (
    <AgentStyledRow hover style={{ cursor: 'pointer' }}>
      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetailsAgent(row)}
            key={column.id}
            align={column.align}
            sx={{
              whiteSpace: 'nowrap',
              py: column.id === 'status' ? 0 : 'inherit',
              maxWidth: '200px',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              ...(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.collaboratorStatus),
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IAgent])}
          </TableCell>
        ))}

      <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <TableActionColumn
          handleEdit={() => handleEditAgent(row)}
          onDuplicate={() => handleCopyAgent(row)}
          onToggle={handleStatusChange}
          isActive={row.userStatus === UserStatus.ACTIF}
          tooltipTitles={TOOLTIP_TITLES}
        />
      </TableCell>
    </AgentStyledRow>
  );
}
