import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import { IAvenant } from '@/shared/types/circuit';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { useTheme } from '@mui/material/styles';
import SvgColor from '@/shared/components/svg-color';
import { ContratStyledRow, getStatusColor, StatusChip } from '../../contract/styles';
import { TableColumn } from '@/shared/types/common';
import { dateFormat, formatDate } from '@/utils/format-time';
import { _CIRCUIT_STATUS, getEtatLabel } from '@/shared/_mock/_circuit';
import StatusMenu from '@/shared/components/table/StatusMenu';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useAmendmentStore } from '@/shared/api/stores/amendmentStore';
import { AmendmentListDTO } from '@/shared/types/amendment';

type Props = {
  handleEditAvenant: (avenant:IAvenant) => void;
  handleDetailsAvenant: (avenant:IAvenant) => void;
  selected: boolean;
  row: IAvenant;
  dense: boolean;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
  onStatusChange: (row: IAvenant, newStatus: string, field: keyof IAvenant) => void;
};

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

export default function AvenantTableRow({
  dense,
  row,
  handleEditAvenant,
  handleDetailsAvenant,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
}: Props) {
  const { cacheRowData } = useAmendmentStore();

  // Convert IAvenant to AmendmentListDTO for caching
  const convertToAmendmentListDTO = (avenant: IAvenant): AmendmentListDTO => ({
    id: avenant.id,
    createdAt: avenant.dateApplication || '',
    controlled: avenant.etat === 'controle',
    amendmentCode: avenant.codeAvenant || '',
    subject: avenant.intitule || '',
    client: avenant.clientDO || '',
    driver: avenant.chauffeur || '',
    company: avenant.departement || '',
    circuitCode: avenant.codeCircuit || '',
    amendmentObject: avenant.objetAvenant || '',
    type: avenant.type || '',
    endDate: avenant.dateFin || '',
    establishment: avenant.etablissement || '',
    active: avenant.isActive,
    object: avenant.objet || '',
    applicationDate: avenant.dateApplication || '',
    status: avenant.etat || '',
    title: avenant.intitule || '',
    amendmentPurpose: avenant.objetAvenant || '',
    clientDO: avenant.clientDO || '',
    purpose: avenant.objet || ''
  });

  const handleRowDoubleClick = () => {
    // Cache the row data before navigation
    const amendmentData = convertToAmendmentListDTO(row);
    cacheRowData(row.id, amendmentData);

    // Then handle the details view
    handleDetailsAvenant(row);
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateApplication':
      case 'dateFin':
        return formatDate(value, dateFormat.isoDate);
      case 'etat':
        return (
          <StatusMenu
            value={value}
            options={_CIRCUIT_STATUS}
            onChange={(newStatus) => onStatusChange(row, newStatus, 'etat')}
            chipComponent={StatusChip}
          />
        );
      default:
        return value;
    }
  };

  return (
    <ContratStyledRow hover
    style={{ cursor: 'pointer' }}>
      {columns
        .filter((column) => column.id !== 'isActive')
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={handleRowDoubleClick}
            key={column.id}
            align={column.align }
            sx={{ whiteSpace: 'nowrap', py: column.id === 'status' ? 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: getStatusColor(row.etat),
              }}
            />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IAvenant])}
          </TableCell>
        ))}

      <TableCell align="center" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <TableActionColumn
          onToggle={() => void 0}
          isActive={row.isActive}
          tooltipTitles={TOOLTIP_TITLES}
        />
      </TableCell>
    </ContratStyledRow>
  );
}
