import { Button, Group, NumberInput, Select, Tooltip } from '@mantine/core';
import { IconPlus } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { useLocalized, type LicenseType } from '@ema-platform/api';
import { groupedTypeOptions } from '../config/designer';

interface Props {
  licenseTypes: LicenseType[];
  typeId: string | null;
  onTypeChange: (id: string | null) => void;
  validityMonths: number;
  onValidityChange: (months: number) => void;
  currentValidityMonths?: number | null;
  canEdit: boolean;
  savingValidity: boolean;
  onSaveValidity: () => void;
  onNewVersion: () => void;
}

/** Licence type, certificate validity, and the entry point for a new version. */
export function DesignerToolbar({
  licenseTypes,
  typeId,
  onTypeChange,
  validityMonths,
  onValidityChange,
  currentValidityMonths,
  canEdit,
  savingValidity,
  onSaveValidity,
  onNewVersion,
}: Props) {
  const { t } = useTranslation();
  const localized = useLocalized();

  return (
    <Group align="flex-end" mb="md" gap="sm">
      {/* Grouped and searchable because the catalogue is 80+ types, over 50 of
          them STCW certificates: a flat list buries the CoC/CoP a user is
          looking for among the logistics operator licences. */}
      <Select
        label={t('designer.licenceType', 'Licence type')}
        data={groupedTypeOptions(licenseTypes, localized, t)}
        value={typeId}
        onChange={onTypeChange}
        searchable
        nothingFoundMessage={t('designer.noTypeMatch', 'No licence type matches')}
        maxDropdownHeight={340}
        w={340}
      />

      {/* Validity lives beside the design because it is the other half of
          what a certificate promises. */}
      <NumberInput
        label={t('designer.validityYears', 'Valid for (years)')}
        description={t('designer.validityHint', 'Applied when a licence is issued')}
        value={Number((validityMonths / 12).toFixed(2))}
        onChange={(value) => onValidityChange(Math.round(Number(value || 0) * 12))}
        min={0.5}
        max={20}
        step={0.5}
        decimalScale={1}
        w={190}
        disabled={!canEdit}
      />
      <Tooltip
        label={
          canEdit
            ? t('designer.saveValidity', 'Save validity')
            : t('designer.noPermission', 'You do not have permission')
        }
      >
        <span>
          <Button
            variant="light"
            loading={savingValidity}
            disabled={!canEdit || !typeId || validityMonths === currentValidityMonths}
            onClick={onSaveValidity}
          >
            {t('designer.saveValidity', 'Save validity')}
          </Button>
        </span>
      </Tooltip>

      <div style={{ flex: 1 }} />

      <Button
        leftSection={<IconPlus size={16} />}
        disabled={!canEdit || !typeId}
        onClick={onNewVersion}
      >
        {t('designer.newVersion', 'New version')}
      </Button>
    </Group>
  );
}
