import type { FunctionalComponent } from 'preact';

import { Checkbox } from '../../core/Checkbox';
import { SectionCard } from '../../core/SectionCard';
import { FormGrid, SelectField, TextField } from '../../forms';
import type {
  AsukaParametricDefinition,
  AsukaParametricVariationControls,
} from '../../../types/parametric3d';

type Props = {
  t: (key: string, fallback?: string) => string;
  form: any;
};

const getDefinition = (form: any): AsukaParametricDefinition | null => {
  const value = form?.values?.parametric;
  return value && value.schemaVersion === 1 && Array.isArray(value.parameters) ? value : null;
};

export const ElementParametricVariationControlsField: FunctionalComponent<Props> = ({ t, form }) => {
  const definition = getDefinition(form);
  if (!definition) return null;

  const current = (definition.ui?.variationControls ?? {}) as AsukaParametricVariationControls;

  const patch = (changes: Partial<AsukaParametricVariationControls>) => {
    form.setValue('parametric', {
      ...definition,
      ui: {
        ...(definition.ui ?? {}),
        variationControls: {
          ...current,
          ...changes,
        },
      },
    });
  };

  return (
    <SectionCard
      variant="subtle"
      title={t('elements.parametric.variationControlsTitle', 'Dimensions in Variations')}
      description={t('elements.parametric.variationControlsDescriptionInline', 'Enable the customer-facing dimension controls, then assign parameters directly inside each Product 3D variation or part below.')}
      className="ask-mb-4"
    >
      <div className="ask-flex ask-flex-col ask-gap-4">
        <Checkbox
          checked={current.enabled === true}
          label={t('elements.parametric.enableVariationControls', 'Show dimensions and parameters in Variations')}
          onChange={(event: any) => patch({
            enabled: !!event.currentTarget?.checked,
            scopes: Array.isArray(current.scopes) ? current.scopes : [],
          })}
        />

        {current.enabled === true ? (
          <>
            <FormGrid columns={2} className="max-lg:ask-grid-cols-1">
              <SelectField
                label={t('elements.parametric.controlsPlacement', 'Position in the current variation list')}
                value={current.placement === 'after' ? 'after' : 'before'}
                options={[
                  { value: 'before', label: t('elements.parametric.beforeVariations', 'Before variations') },
                  { value: 'after', label: t('elements.parametric.afterVariations', 'After variations') },
                ]}
                onValueChange={(value) => patch({ placement: value === 'after' ? 'after' : 'before' })}
              />
              <TextField
                label={t('elements.parametric.controlsHeading', 'Default heading')}
                placeholder={t('parametric3d.variationControlsTitle', 'Dimensions & parameters')}
                value={String(current.title ?? '')}
                onValueChange={(value) => patch({ title: value })}
              />
              <TextField
                fieldClassName="ask-col-span-2 max-lg:ask-col-span-1"
                label={t('elements.parametric.controlsDescription', 'Default helper text')}
                value={String(current.description ?? '')}
                onValueChange={(value) => patch({ description: value })}
              />
            </FormGrid>

            <div className="ask-rounded-2xl ask-border ask-border-borderSubtle ask-bg-surfaceAlt ask-p-3 ask-text-[11px] ask-leading-5 ask-text-textMuted">
              {t('elements.parametric.inlineAssignmentHint', 'Parameter assignment is now done in context: open a Product 3D variation or detected part below and choose the dimensions that belong to that specific customer step.')}
            </div>

            <Checkbox
              checked={current.compact !== false}
              label={t('elements.parametric.compactControls', 'Use compact controls inside Variations')}
              onChange={(event: any) => patch({ compact: !!event.currentTarget?.checked })}
            />
          </>
        ) : null}
      </div>
    </SectionCard>
  );
};

export default ElementParametricVariationControlsField;
