import {
  Button,
  Group,
  Image,
  NumberInput,
  Paper,
  SegmentedControl,
  Select,
  Stack,
  Text,
  TextInput,
} from '@mantine/core';
import { IconPhotoUp, IconTrash } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import type { TemplateLogoCorner, TemplateLogoPlacement } from '@ema-platform/api';

interface Props {
  backgroundUrl: string;
  onBackgroundChange: (url: string) => void;
  logoUrl: string;
  onLogoChange: (url: string) => void;
  logoPlacement: TemplateLogoPlacement;
  onLogoPlacementChange: (placement: TemplateLogoPlacement) => void;
  landscape: boolean;
  onLandscapeChange: (landscape: boolean) => void;
  pageWidth: string;
  onPageWidthChange: (width: string) => void;
  pageHeight: string;
  onPageHeightChange: (height: string) => void;
  disabled: boolean;
}

const CORNERS: { value: TemplateLogoCorner; labelKey: string; fallback: string }[] = [
  { value: 'TOP_LEFT', labelKey: 'designer.cornerTopLeft', fallback: 'Top left' },
  { value: 'TOP_CENTER', labelKey: 'designer.cornerTopCenter', fallback: 'Top centre' },
  { value: 'TOP_RIGHT', labelKey: 'designer.cornerTopRight', fallback: 'Top right' },
  { value: 'BOTTOM_LEFT', labelKey: 'designer.cornerBottomLeft', fallback: 'Bottom left' },
  { value: 'BOTTOM_RIGHT', labelKey: 'designer.cornerBottomRight', fallback: 'Bottom right' },
];

/**
 * Page-level settings: orientation, the artwork a certificate is printed on,
 * and the authority's logo.
 *
 * Orientation belongs here rather than beside the version name because it is a
 * property of the page, and it decides the shape of the canvas everything else
 * is positioned on.
 */
export function TemplateBackgroundPanel({
  backgroundUrl,
  onBackgroundChange,
  logoUrl,
  onLogoChange,
  logoPlacement,
  onLogoPlacementChange,
  landscape,
  onLandscapeChange,
  pageWidth,
  onPageWidthChange,
  pageHeight,
  onPageHeightChange,
  disabled,
}: Props) {
  const { t } = useTranslation();

  return (
    <Paper withBorder p="md" radius="md">
      <Stack gap="sm">
        <div>
          <Text fw={600} size="sm">
            {t('designer.pageSetup', 'Page setup')}
          </Text>
          <Text size="xs" c="dimmed">
            {t(
              'designer.pageSetupHint',
              'Orientation, background artwork and the authority logo. Certificate data is drawn on top, so the same page serves every certificate.',
            )}
          </Text>
        </div>

        <Group gap="xl" align="flex-start">
          <div>
            <Text size="sm" fw={500} mb={4}>
              {t('designer.orientation', 'Orientation')}
            </Text>
            <SegmentedControl
              value={landscape ? 'landscape' : 'portrait'}
              onChange={(value) => onLandscapeChange(value === 'landscape')}
              disabled={disabled}
              data={[
                {
                  value: 'portrait',
                  label: t('designer.portrait', 'Portrait'),
                },
                {
                  value: 'landscape',
                  label: t('designer.landscape', 'Landscape'),
                },
              ]}
            />
            <Text size="xs" c="dimmed" mt={4}>
              {pageWidth && pageHeight
                ? t('designer.customSize', 'Custom size — see below')
                : landscape
                  ? t('designer.a4Landscape', 'A4 — 297 × 210 mm')
                  : t('designer.a4Portrait', 'A4 — 210 × 297 mm')}
            </Text>
          </div>

          <div>
            <Text size="sm" fw={500} mb={4}>
              {t('designer.customPageSize', 'Custom page size')}
            </Text>
            <Group gap="xs">
              <TextInput
                placeholder={t('designer.pageWidth', 'Width')}
                value={pageWidth}
                onChange={(e) => onPageWidthChange(e.currentTarget.value)}
                disabled={disabled}
                w={100}
              />
              <Text size="sm" c="dimmed">×</Text>
              <TextInput
                placeholder={t('designer.pageHeight', 'Height')}
                value={pageHeight}
                onChange={(e) => onPageHeightChange(e.currentTarget.value)}
                disabled={disabled}
                w={100}
              />
            </Group>
            <Text size="xs" c="dimmed" mt={4}>
              {t(
                'designer.customSizeHint',
                'e.g. 4.92in × 3.46in. Leave both blank to use A4. Overrides orientation\'s A4 size when set.',
              )}
            </Text>
          </div>
        </Group>

        <Group align="flex-end" gap="sm">
          <TextInput
            label={t('designer.backgroundUrl', 'Artwork URL')}
            placeholder="https://…"
            value={backgroundUrl}
            onChange={(e) => onBackgroundChange(e.currentTarget.value)}
            disabled={disabled}
            style={{ flex: 1 }}
          />
          {backgroundUrl && (
            <Button
              variant="subtle"
              color="red"
              leftSection={<IconTrash size={16} />}
              disabled={disabled}
              onClick={() => onBackgroundChange('')}
            >
              {t('designer.removeBackground', 'Remove')}
            </Button>
          )}
        </Group>

        {backgroundUrl ? (
          <Image
            src={backgroundUrl}
            alt={t('designer.backgroundPreview', 'Certificate background preview')}
            radius="sm"
            fit="contain"
            mah={220}
            fallbackSrc="data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E"
          />
        ) : (
          <Paper withBorder p="lg" radius="sm" bg="var(--mantine-color-gray-light)">
            <Group justify="center" gap="xs">
              <IconPhotoUp size={18} />
              <Text size="sm" c="dimmed">
                {t('designer.noBackground', 'No artwork — the design renders as HTML only.')}
              </Text>
            </Group>
          </Paper>
        )}

        <Group align="flex-end" gap="sm">
          <TextInput
            label={t('designer.logoUrl', 'Institute logo URL')}
            placeholder="https://…"
            value={logoUrl}
            onChange={(e) => onLogoChange(e.currentTarget.value)}
            disabled={disabled}
            style={{ flex: 1 }}
          />
          {logoUrl && (
            <Button
              variant="subtle"
              color="red"
              leftSection={<IconTrash size={16} />}
              disabled={disabled}
              onClick={() => onLogoChange('')}
            >
              {t('designer.removeLogo', 'Remove')}
            </Button>
          )}
        </Group>

        {logoUrl && (
          <Group align="flex-end" gap="sm">
            <Select
              label={t('designer.logoCorner', 'Logo position')}
              data={CORNERS.map((corner) => ({
                value: corner.value,
                label: t(corner.labelKey, corner.fallback),
              }))}
              value={logoPlacement.corner ?? 'TOP_LEFT'}
              onChange={(value) =>
                onLogoPlacementChange({
                  ...logoPlacement,
                  corner: (value as TemplateLogoCorner) ?? 'TOP_LEFT',
                })
              }
              disabled={disabled}
              w={170}
            />
            <NumberInput
              label={t('designer.logoWidth', 'Width (% of page)')}
              value={logoPlacement.widthPct ?? 18}
              onChange={(value) =>
                onLogoPlacementChange({
                  ...logoPlacement,
                  widthPct: Number(value) || 0,
                })
              }
              min={1}
              max={100}
              disabled={disabled}
              w={150}
            />
            <NumberInput
              label={t('designer.logoOffset', 'Inset (%)')}
              value={logoPlacement.offsetPct ?? 5}
              onChange={(value) =>
                onLogoPlacementChange({
                  ...logoPlacement,
                  offsetPct: Number(value) || 0,
                })
              }
              min={0}
              max={100}
              disabled={disabled}
              w={120}
            />
            <Image
              src={logoUrl}
              alt={t('designer.logoPreview', 'Logo preview')}
              radius="sm"
              fit="contain"
              h={56}
              w={56}
              fallbackSrc="data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E"
            />
          </Group>
        )}
      </Stack>
    </Paper>
  );
}
