import React from 'react';
import Checkbox from '@mui/material/Checkbox';
import TableCell from '@mui/material/TableCell';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { 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 { getBillingTerms, getPortalStatus, getTypeTerms } from '@/shared/_mock/_client';
import { IClient, UserStatus } from '@/shared/types/client';
import { ContratStyledRow, getStatusColor, StatusChip } from '../../contract/styles';
import { Chip } from '@mui/material';
import { useClientStore } from '@/shared/api/stores/userStore';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

type Props = {
  handleEdit: (contrat: IClient) => void;
  handleDetails: (contrat: IClient) => void;
  handleCopy: (contrat: IClient) => void;
  selected: boolean;
  dense: boolean;
  row: IClient;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
};
const TOOLTIP_TITLES = {
  edit: 'Modifier client',
  duplicate: 'Copier client',
  active: 'client actif',
  inactive: 'client inactif',
};

export default function ClientTableRow({
  row,
  handleEdit,
  handleDetails,
  handleCopy,
  selected,
  dense,
  onSelectRow,
  columns,
}: Props) {
  const theme = useTheme();
  const { clients, toggleClientActive } = useClientStore();

  const renderCellContent = (columnId: string, value: any, row: IClient) => {
    if (value === null || value === undefined || value === '') return '-';

    if (typeof value === 'object') {
      if ('name' in value) return value.name || '-';
      return JSON.stringify(value) || '-';
    }

    switch (columnId) {
      case 'birthDate':
      case 'signatureDate':
      case 'paymentDate':
        return value ? formatDate(value, dateFormat.isoDate) : '-';

      case 'portalAssignment':
      case 'mainBranch':
        return value === 'CLIENT' ? 'Client' : value === 'TAD' ? 'TAD' : value || '-';

      case 'typeClient':
        return value === 'CLIENT_DO' ? "Donneur d'ordre" : value === 'OTHERS' ? 'Autre' : value || '-';

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

  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}>
      {columns.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: row.colorCode?.toString(),
              }}
            />
          </ConditionalComponent>
          {renderCellContent(column.id, row[column.id as keyof IClient], row)}
        </TableCell>
      ))}

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