import { Button, Code, ScrollArea, Stack, Text, Tooltip } from '@mantine/core';
import { IconPhoto, IconPlus } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import type { TemplateVariable } from '@ema-platform/api';

interface Props {
  variables: TemplateVariable[];
  disabled: boolean;
  /** Canvas mode: drops a block onto the page. Source mode: inserts at caret. */
  canvasMode: boolean;
  onInsert: (key: string) => void;
  onAddBlock: (key: string, kind: 'text' | 'image') => void;
  onAddTextBlock: () => void;
}

/** Placeholders the design can carry — dropped on the page, or typed at the caret. */
export function TemplateVariableList({
  variables,
  disabled,
  canvasMode,
  onInsert,
  onAddBlock,
  onAddTextBlock,
}: Props) {
  const { t } = useTranslation();

  return (
    <Stack gap="xs" w={230} style={{ flexShrink: 0 }}>
      <Text fw={600} size="sm">
        {t('designer.variables', 'Placeholders')}
      </Text>
      <Text size="xs" c="dimmed">
        {canvasMode
          ? t('designer.variablesCanvasHint', 'Click to add a block to the page.')
          : t('designer.variablesHint', 'Click to insert at the cursor.')}
      </Text>

      {canvasMode && (
        <Button
          size="compact-xs"
          variant="light"
          leftSection={<IconPlus size={13} />}
          disabled={disabled}
          onClick={onAddTextBlock}
        >
          {t('designer.addTextBlock', 'Fixed text block')}
        </Button>
      )}

      <ScrollArea.Autosize mah={480} type="hover">
        <Stack gap={4}>
          {variables.map((variable) => (
            <Tooltip key={variable.key} label={variable.label} position="left">
              <Button
                size="compact-xs"
                variant="default"
                justify="flex-start"
                disabled={disabled}
                leftSection={
                  variable.kind === 'image' ? <IconPhoto size={12} /> : undefined
                }
                onClick={() =>
                  canvasMode
                    ? onAddBlock(variable.key, variable.kind === 'image' ? 'image' : 'text')
                    : onInsert(variable.key)
                }
              >
                <Code fz={10}>{`{{${variable.key}}}`}</Code>
              </Button>
            </Tooltip>
          ))}
        </Stack>
      </ScrollArea.Autosize>
    </Stack>
  );
}
