import { memo, useMemo } from 'react';

import Checkbox from '@material-hu/components/design-system/Checkbox/Checkbox';
import Pills, {
  type PillsProps,
} from '@material-hu/components/design-system/Pills';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';
import TableRowComponent from '@material-hu/components/design-system/Table/components/TableRow';

import {
  type SessionAttendance,
  type SessionStatusType,
} from 'src/pages/dashboard/Learning/Sessions/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { TableActions } from './TableActions';

type TableRowProps = {
  sessionStatus?: SessionStatusType;
  sessionId?: number;
  collaborator: SessionAttendance;
  onSelectCollaborator: (userId: number) => void;
  checked: boolean;
};

export const TableRow = memo(
  ({
    collaborator,
    sessionStatus,
    sessionId,
    onSelectCollaborator,
    checked,
  }: TableRowProps) => {
    const { t } = useLokaliseTranslation('learning');

    const pillConfig = useMemo(() => {
      const config: PillsProps = {
        label: '',
        type: 'neutral',
        hasIcon: false,
      };

      if (collaborator.assisted) {
        config.label = t('common.present_one');
        config.type = 'success';
      } else if (collaborator.assisted === null) {
        config.label = t('common.with_no_configuration');
        config.type = 'disabled';
      } else {
        config.label = t('common.absent_one');
        config.type = 'neutral';
      }

      return config;
    }, [collaborator.assisted]);

    return (
      <TableRowComponent
        selected={checked}
        aria-checked={checked}
        hover
        key={collaborator.id}
        role="checkbox"
        tabIndex={-1}
        sx={{ cursor: 'pointer' }}
      >
        <TableCell
          selectionCell
          padding="checkbox"
          sx={{ borderWidth: 1 }}
        >
          <Checkbox
            onClick={event => {
              (event.target as HTMLElement).blur();
              onSelectCollaborator(collaborator.userId);
            }}
            checked={checked}
            aria-label={`${t('general:select')} ${collaborator.fullName}`}
          />
        </TableCell>
        <TableCell>{collaborator.fullName}</TableCell>
        <TableCell>
          {collaborator.confirmedAssistance
            ? t('general:yes')
            : t('common.pending_answer')}
        </TableCell>
        <TableCell>
          <Pills
            size="small"
            {...pillConfig}
          />
        </TableCell>
        <TableActions
          sessionStatus={sessionStatus}
          sessionId={sessionId}
          collaborator={collaborator}
        />
      </TableRowComponent>
    );
  },
);

TableRow.displayName = 'TableRow';
