import type { ReactNode } from 'react';
import { Checkbox, Text, TextInput } from '@mantine/core';
import type { TFunction } from 'i18next';
import type { ApplicationStaff } from '@ema-platform/api';
import type { AdvancedColumn } from '@ema-platform/ui';

export function reviewStaffColumns(
  t: TFunction,
  handlers: {
    flags: Record<string, { remark: string }>;
    /** Bilingual role label resolved from the licence-type config. */
    roleName: (member: ApplicationStaff) => string;
    /** Evidence badges — needs an attachments query, so the page supplies it. */
    renderEvidence: (member: ApplicationStaff) => ReactNode;
    onToggleFlag: (member: ApplicationStaff) => void;
    onRemarkChange: (member: ApplicationStaff, remark: string) => void;
  },
): AdvancedColumn<ApplicationStaff>[] {
  const { flags } = handlers;
  return [
    {
      header: t('review.role', 'Role'),
      cell: ({ row }) => <Text size="xs">{handlers.roleName(row.original)}</Text>,
    },
    {
      header: t('review.name', 'Name'),
      cell: ({ row }) => <Text size="sm">{row.original.fullName}</Text>,
    },
    {
      header: t('review.evidence', 'Evidence'),
      cell: ({ row }) => handlers.renderEvidence(row.original),
    },
    {
      // A person's papers are as returnable as a document or a form section:
      // an ERB certificate for the wrong person is a defect the applicant has
      // to fix, and until now the officer had to describe it under some
      // unrelated document.
      header: t('review.correction', 'Correction'),
      size: 260,
      cell: ({ row }) => {
        const member = row.original;
        return (
          <>
            <Checkbox
              size="xs"
              label={t('review.needsCorrection', 'Needs correction')}
              checked={Boolean(flags[member.id])}
              onChange={() => handlers.onToggleFlag(member)}
            />
            {flags[member.id] && (
              <TextInput
                mt={6}
                size="xs"
                withAsterisk
                placeholder={t(
                  'review.correctionPlaceholder',
                  'What must the applicant correct?',
                )}
                error={
                  flags[member.id].remark.trim()
                    ? null
                    : t('review.correctionRequired', 'Say what must be corrected')
                }
                value={flags[member.id].remark}
                onChange={(e) => {
                  const remark = e.currentTarget.value;
                  handlers.onRemarkChange(member, remark);
                }}
              />
            )}
          </>
        );
      },
    },
  ];
}
