import type { FunctionalComponent } from 'preact';

import { Badge, SectionCard } from '../../core';
import { FormGrid, SelectField } from '../../forms';

type Option = { value: string; label: string };

type ElementCopyFromViewPanelProps = {
  t: (key: string, fallback?: string) => string;
  copyViewOptions: Option[];
  copyElementOptions: Option[];
  copyFromViewId: string;
  copyFromElementObjectId: string;
  copiedPlacementProps?: any;
  copiedVariationId?: string;
  onSourceViewChange: (value: string) => void;
  onSourceElementChange: (value: string) => void;
};

export const ElementCopyFromViewPanel: FunctionalComponent<ElementCopyFromViewPanelProps> = ({
  t,
  copyViewOptions,
  copyElementOptions,
  copyFromViewId,
  copyFromElementObjectId,
  copiedPlacementProps,
  copiedVariationId,
  onSourceViewChange,
  onSourceElementChange,
}) => {
  if (!copyViewOptions.length) return null;

  return (
    <SectionCard
      title={t('elements.copy.title', 'Copy from another view')}
      description={t('elements.copy.helper', 'Reuse an existing element definition and its placement as a starting point.')}
      contentClassName="ask-space-y-3"
    >
      <FormGrid columns={2}>
        <SelectField
          label={t('elements.copy.sourceView', 'Source view')}
          value={copyFromViewId}
          onValueChange={(value) => onSourceViewChange(String(value ?? ''))}
          options={[{ value: '', label: '—' }, ...copyViewOptions]}
        />
        <SelectField
          label={t('elements.copy.sourceElement', 'Source element')}
          value={copyFromElementObjectId}
          disabled={!copyFromViewId}
          onValueChange={(value) => onSourceElementChange(String(value ?? ''))}
          options={[{ value: '', label: '—' }, ...copyElementOptions]}
        />
      </FormGrid>
      {copyFromElementObjectId && copiedPlacementProps ? (
        <Badge variant="surface" size="sm">
          {t('elements.copy.success', 'Placement copied')} • {t('elements.copy.variationId', 'Variation ID')}: {copiedVariationId || '—'}
        </Badge>
      ) : null}
    </SectionCard>
  );
};
