import { ActionIcon, Button, Group } from '@mantine/core';
import { IconEdit, IconGavel, IconSend, 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 { Question } from '../../types/question';

export function questionActionsColumn(
  t: TFunction,
  handlers: {
    isSubmittingReview: boolean;
    onSubmitForApproval: (question: Question) => void;
    onReview: (question: Question, outcome: 'APPROVED' | 'REJECTED' | 'RETIRED') => void;
    onEdit: (question: Question) => void;
    onDelete: (question: Question) => void;
  },
): AdvancedColumn<Question> {
  return {
    header: '',
    label: t('question.columns.actions', 'Actions'),
    cell: ({ row }) => {
      const q = row.original;
      return (
        <Group gap="xs">
          {(q.status === 'DRAFT' || q.status === 'REJECTED') && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.AUTHOR_QUESTION]} hideOnly>
              <Button
                size="compact-xs"
                variant="light"
                leftSection={<IconSend size={12} />}
                loading={handlers.isSubmittingReview}
                onClick={() => handlers.onSubmitForApproval(q)}
              >
                {t('question.qc.submit')}
              </Button>
            </RequirePermission>
          )}
          {q.status === 'PENDING_APPROVAL' && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_QUESTION]} hideOnly>
              <Button size="compact-xs" variant="light" color="teal" onClick={() => handlers.onReview(q, 'APPROVED')}>
                {t('question.qc.approve')}
              </Button>
              <Button size="compact-xs" variant="light" color="red" onClick={() => handlers.onReview(q, 'REJECTED')}>
                {t('question.qc.reject')}
              </Button>
            </RequirePermission>
          )}
          {q.status === 'APPROVED' && (
            <RequirePermission anyOf={[LICENSE_PERMISSIONS.APPROVE_QUESTION]} hideOnly>
              <Button
                size="compact-xs"
                variant="subtle"
                color="dark"
                leftSection={<IconGavel size={12} />}
                onClick={() => handlers.onReview(q, 'RETIRED')}
              >
                {t('question.qc.retire')}
              </Button>
            </RequirePermission>
          )}
          <RequirePermission anyOf={[LICENSE_PERMISSIONS.AUTHOR_QUESTION]} hideOnly>
            <ActionIcon variant="subtle" color="blue" size="sm" onClick={() => handlers.onEdit(q)}>
              <IconEdit size={14} />
            </ActionIcon>
            <ActionIcon variant="subtle" color="red" size="sm" onClick={() => handlers.onDelete(q)}>
              <IconTrash size={14} />
            </ActionIcon>
          </RequirePermission>
        </Group>
      );
    },
  };
}
