'use client';

import TableCell from '@mui/material/TableCell';
import TableActionColumn from '@/shared/components/table/table-action-column';
import type { TableColumn } from '@/shared/types/common';
import { ContratStyledRow } from '@/shared/sections/contract/styles';
import { CoverageZoneLabels, InterventionType, InterventionTypeLabels, ServiceProvider } from '@/shared/types/fleet-management/service-provider';
import { useServiceProviderStore } from '@/shared/api/stores/fleet-service/service-provider-store';

type Props = {
  handleEditServiceProvider: (serviceProvider: ServiceProvider) => void;
  handleDetailsServiceProvider: (serviceProvider: ServiceProvider) => void;
  handleDuplicateServiceProvider: (serviceProvider: ServiceProvider) => void;
  row: ServiceProvider;
  columns: TableColumn[];
};

const TOOLTIP_TITLES = {
  edit: "Modifier fournisseur",
  duplicate: "Copier fournisseur",
  active: "Fournisseur actif",
  inactive: "Fournisseur inactif",
};

export default function ServiceProviderTableRow({
  row,
  handleEditServiceProvider,
  handleDetailsServiceProvider,
  handleDuplicateServiceProvider,
  columns,
}: Props) {

  const { toggleActive } = useServiceProviderStore();

  const handleToggleActivation = async (isActive: boolean) => {
    await toggleActive(row.id, isActive);
  }

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "coverageZone":
        return CoverageZoneLabels[row.coverageZone];
      case "intervention":
        return row.intervention.name;
      case "interventionType":
        return InterventionTypeLabels[row.intervention.interventionType];
      case "amount":
        return value + " €";
      default:
        return value;
    }
  };

  return (
    <ContratStyledRow hover style={{ cursor: 'pointer' }}>
      {columns.filter((c) => c.id !== 'isActive').map((column: any, index: number) => (
        <TableCell
          onDoubleClick={() => handleDetailsServiceProvider(row)}
          key={column.id}
          align={column.align}
          sx={{ whiteSpace: 'nowrap', py: column.id === 'active' ? 0 : 'inherit' }}
        >
          {renderCellContent(column.id, row[column.id as keyof ServiceProvider])}
        </TableCell>
      ))}

      <TableCell align="right" sx={{ px: 1, whiteSpace: 'nowrap' }}>
        <TableActionColumn
          handleEdit={() => handleEditServiceProvider(row)}
          onToggle={(checked) => handleToggleActivation(checked)}
          onDuplicate={() => handleDuplicateServiceProvider(row)}
          isActive={row.active}
          tooltipTitles={TOOLTIP_TITLES}
        />
      </TableCell>
    </ContratStyledRow>
  );
}