import { Button, Group } from '@mantine/core';
import { IconEye, IconTrash } from '@tabler/icons-react';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import { LICENSE_PERMISSIONS, RequirePermission } from '@ema-platform/auth';
import type { Result } from '../../types/result';

export type QcAction = 'moderate' | 'approve' | 'return';

export function resultActionsColumn(
  t: TFunction,
  handlers: {
    onQc: (result: Result, action: QcAction) => void;
    onViewDetail: (result: Result) => void;
    onDelete: (result: Result) => void;
  },
): AdvancedColumn<Result> {
  return {
    header: '',
    label: t('result.columns.actions', 'Actions'),
    cell: ({ row }) => {
      const r = row.original;
      return (
        <Group gap="xs">
          {(r.reviewStatus === 'MARKED' || r.reviewStatus === 'MODERATED') && (
            <>
              <RequirePermission anyOf={[LICENSE_PERMISSIONS.MODERATE_EXAM_RESULT]} hideOnly>
                <Button size="compact-xs" variant="light" color="yellow" onClick={() => handlers.onQc(r, 'moderate')}>
                  {t('result.review.moderate')}
                </Button>
              </RequirePermission>
              <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_EXAM_RESULT]} hideOnly>
                <Button size="compact-xs" variant="light" color="blue" onClick={() => handlers.onQc(r, 'approve')}>
                  {t('result.review.approve')}
                </Button>
              </RequirePermission>
            </>
          )}
          {(r.reviewStatus === 'APPROVED' || r.reviewStatus === 'MODERATED') && (
            <RequirePermission
              anyOf={[
                LICENSE_PERMISSIONS.MODERATE_EXAM_RESULT,
                LICENSE_PERMISSIONS.APPROVE_EXAM_RESULT,
              ]}
              hideOnly
            >
              <Button size="compact-xs" variant="subtle" color="orange" onClick={() => handlers.onQc(r, 'return')}>
                {t('result.review.return')}
              </Button>
            </RequirePermission>
          )}
          <Button size="xs" variant="subtle" leftSection={<IconEye size={13} />} onClick={() => handlers.onViewDetail(r)}>
            {t('result.action.viewEdit')}
          </Button>
          <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_EXAM_RESULT]} hideOnly>
            <Button
              size="xs"
              variant="subtle"
              color="red"
              leftSection={<IconTrash size={13} />}
              onClick={() => handlers.onDelete(r)}
            >
              {t('result.action.delete')}
            </Button>
          </RequirePermission>
        </Group>
      );
    },
  };
}
