import { Button, Group } from '@mantine/core';
import { IconDownload, IconTrash } from '@tabler/icons-react';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import type { LicenseApplication } from '@ema-platform/api';
import { PORTAL_PERMISSIONS } from '@ema-platform/auth';
import { ExamStageActions } from '../../components/ExamStageActions';

/** Statuses whose primary action is supplied by {@link ExamStageActions}. */
const EXAM_STAGE_STATUSES = [
  'ELIGIBILITY_PAYMENT_PENDING',
  'ELIGIBILITY_PAID',
  'EXAM_PAYMENT_PENDING',
  'EXAM_PAID',
  'EXAM_SCHEDULED',
  'EXAM_FAILED',
  'EXAM_PASSED',
];

export function applicationActionsColumn(
  t: TFunction,
  deps: {
    /** Permission check from usePermissions() — hooks can't run in a cell. */
    can: (required?: string[]) => boolean;
    bypassEnabled: boolean;
    bypassing: boolean;
    isPaying: boolean;
    /** True while a resit is being requested. */
    requestingExamFee: boolean;
    onBypass: (app: LicenseApplication) => void;
    onCertificate: (app: LicenseApplication) => void;
    onPay: (app: LicenseApplication) => void;
    onRetakeExam: (app: LicenseApplication) => void;
    onRegisterForExam: () => void;
    onOpen: (app: LicenseApplication) => void;
    onDiscard: (app: LicenseApplication) => void;
  },
): AdvancedColumn<LicenseApplication> {
  return {
    header: '',
    label: t('common.actions'),
    align: 'right',
    cell: ({ row }) => {
      const app = row.original;
      return (
        <Group gap="xs" justify="flex-end" wrap="nowrap">
          {/* Renders only during the exam leg; null everywhere else. */}
          <ExamStageActions
            app={app}
            t={t}
            requesting={deps.requestingExamFee}
            paying={deps.isPaying}
            onRetakeExam={deps.onRetakeExam}
            onPay={deps.onPay}
            onRegisterForExam={deps.onRegisterForExam}
          />
          {/* Every fee stop is bypassable — an examined certificate charges
              three separate fees (eligibility, exam, certificate) and is
              otherwise untestable without a live gateway. */}
          {deps.bypassEnabled &&
            (app.status === 'PAYMENT_PENDING' ||
              app.status === 'ELIGIBILITY_PAYMENT_PENDING' ||
              app.status === 'EXAM_PAYMENT_PENDING' ||
              app.status === 'EXAM_PASSED') && (
            <Button
              size="xs"
              variant="default"
              loading={deps.bypassing}
              onClick={() => deps.onBypass(app)}
              title="Testing only — marks the fee paid and issues the licence"
            >
              {t('applications.actions.bypass')}
            </Button>
          )}
          {/* An issued application's primary action is the certificate. It
              used to be "View", which opened the application wizard — so
              the one thing the applicant came back for was the one thing
              the button did not do. */}
          {app.status === 'CERTIFICATE_ISSUED' &&
            deps.can([
              PORTAL_PERMISSIONS.VIEW_OWN_CERTIFICATES,
              PORTAL_PERMISSIONS.VIEW_COMPANY_LICENSES,
            ]) && (
            <Button
              size="xs"
              leftSection={<IconDownload size={14} />}
              onClick={() => deps.onCertificate(app)}
            >
              {t('applications.actions.certificate')}
            </Button>
          )}
          {/* In PAYMENT_PENDING this button initiates payment, so it needs
              that grant; every other status it merely opens the wizard.
              Suppressed during the exam leg, where ExamStageActions already
              supplies the action that matters. */}
          {!EXAM_STAGE_STATUSES.includes(app.status) &&
            (app.status !== 'PAYMENT_PENDING' ||
            deps.can([PORTAL_PERMISSIONS.INITIATE_PAYMENT])) && (
          <Button
            size="xs"
            loading={deps.isPaying && app.status === 'PAYMENT_PENDING'}
            variant={
              app.status === 'RESUBMIT_REQUIRED' || app.status === 'PAYMENT_PENDING' ? 'filled' : 'subtle'
            }
            color={
              app.status === 'RESUBMIT_REQUIRED'
                ? 'orange'
                : app.status === 'PAYMENT_PENDING'
                  ? 'yellow'
                  : undefined
            }
            onClick={() =>
              // Paying leaves the SPA for Telebirr, so this is a provider
              // hand-off rather than a route change.
              app.status === 'PAYMENT_PENDING' ? deps.onPay(app) : deps.onOpen(app)
            }
          >
            {app.status === 'DRAFT'
              ? t('applications.actions.continue')
              : app.status === 'RESUBMIT_REQUIRED'
                ? t('applications.actions.fixResubmit')
                : app.status === 'PAYMENT_PENDING'
                  ? t('applications.actions.pay', {
                      amount: Number(app.feeAmount ?? 0).toLocaleString(),
                      currency: app.feeCurrency,
                    })
                  : app.status === 'CERTIFICATE_ISSUED'
                    ? t('applications.actions.certificate')
                    : t('applications.actions.view')}
          </Button>
          )}
          {/* Drafts only: after submission the filing is a record an officer
              may already be reading, so it is withdrawn, not deleted. */}
          {app.status === 'DRAFT' && (
            <Button
              size="xs"
              variant="subtle"
              color="red"
              leftSection={<IconTrash size={14} />}
              onClick={() => deps.onDiscard(app)}
            >
              {t('applications.actions.discard')}
            </Button>
          )}
        </Group>
      );
    },
  };
}
