import React from 'react';
import {
  Box,
  Dropdown,
  listItemSectionBuilder,
  listItemSelectBuilder,
  FormField,
} from '@wix/design-system';
import { getFieldTypeIcon } from '../../../utils/fieldTypePrefixIcons';
import type { SelectableFieldTypes } from '../types';

const OPTIONS = [
  listItemSectionBuilder({
    title: 'Essentials',
    id: 'section-essentials',
    type: 'subheader',
  }),
  listItemSelectBuilder({
    id: 'SHORT_TEXT',
    title: 'Text',
    label: 'Text',
    prefix: (
      <Box>{getFieldTypeIcon({ fieldType: 'SHORT_TEXT', size: 'medium' })}</Box>
    ),
  }),
  listItemSelectBuilder({
    id: 'NUMBER',
    title: 'Number',
    label: 'Number',
    prefix: (
      <Box>{getFieldTypeIcon({ fieldType: 'NUMBER', size: 'medium' })}</Box>
    ),
  }),
  listItemSelectBuilder({
    id: 'BOOLEAN',
    title: 'Boolean',
    label: 'Boolean',
    prefix: (
      <Box>{getFieldTypeIcon({ fieldType: 'BOOLEAN', size: 'medium' })}</Box>
    ),
  }),
  listItemSelectBuilder({
    id: 'DATE',
    title: 'Date',
    label: 'Date',
    prefix: (
      <Box>{getFieldTypeIcon({ fieldType: 'DATE', size: 'medium' })}</Box>
    ),
  }),
];

export interface FieldTypeSelectProps {
  label: string;
  value: SelectableFieldTypes | undefined;
  onChange: (v: SelectableFieldTypes) => void;
  disabled?: boolean;
  error?: string;
}

export const FieldTypeSelect = ({
  label,
  value,
  onChange,
  disabled,
  error,
}: FieldTypeSelectProps) => (
  <FormField
    required
    stretchContent
    label={label}
    status={error ? 'error' : undefined}
    statusMessage={error}
  >
    <Dropdown
      popoverProps={{ zIndex: 10000, appendTo: 'window' }}
      placeholder="Choose a type"
      valueParser={(option) => option.label}
      prefix={
        value
          ? getFieldTypeIcon({ fieldType: value, size: 'medium' })
          : undefined
      }
      options={OPTIONS}
      selectedId={value}
      onSelect={(option) => onChange(option.id as SelectableFieldTypes)}
      disabled={disabled}
    />
  </FormField>
);
