import type { RefObject } from 'react';
import { Group, Paper, Switch, Text, TextInput, Textarea } from '@mantine/core';
import { useTranslation } from 'react-i18next';

interface Props {
  name: string;
  onNameChange: (value: string) => void;
  source: string;
  onSourceChange: (value: string) => void;
  landscape: boolean;
  onLandscapeChange: (value: boolean) => void;
  editorRef: RefObject<HTMLTextAreaElement | null>;
  disabled: boolean;
  isPublished: boolean;
}

/** Name, orientation and the Handlebars source for the selected version. */
export function TemplateEditor({
  name,
  onNameChange,
  source,
  onSourceChange,
  landscape,
  onLandscapeChange,
  editorRef,
  disabled,
  isPublished,
}: Props) {
  const { t } = useTranslation();

  return (
    <>
      <Group gap="sm" align="flex-end">
        <TextInput
          label={t('designer.name', 'Version name')}
          value={name}
          onChange={(e) => onNameChange(e.currentTarget.value)}
          disabled={disabled}
          style={{ flex: 1 }}
        />
        <Switch
          label={t('designer.landscape', 'Landscape')}
          checked={landscape}
          onChange={(e) => onLandscapeChange(e.currentTarget.checked)}
          disabled={disabled}
        />
      </Group>

      {isPublished && (
        <Paper withBorder p="xs" bg="var(--mantine-color-teal-light)">
          <Text size="xs">
            {t(
              'designer.publishedLocked',
              'This version is live and cannot be edited — certificates have been issued from it. Create a new version to make changes.',
            )}
          </Text>
        </Paper>
      )}

      <Textarea
        ref={editorRef}
        label={t('designer.source', 'Template (Handlebars + HTML)')}
        value={source}
        onChange={(e) => onSourceChange(e.currentTarget.value)}
        disabled={disabled}
        autosize
        minRows={18}
        maxRows={30}
        styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
      />
    </>
  );
}
