import { useRef } from 'react';
import * as stylex from '@stylexjs/stylex';

import type { FormCustomField } from '~/src/ui/components/form';

import FontIcon from '~/src/components/Icon/FontIcon';
import MenuIcon from '~/src/components/Icon/MenuIcon';
import MoreIcon from '~/src/components/Icon/MoreIcon';
import SelectComponentIcon from '~/src/components/Icon/SelectComponentIcon';
import TickIcon from '~/src/components/Icon/TickIcon';
import { LayoutGrid } from '~/src/ui/layouts/layoutGrid';
import { Tile } from '~/src/ui/layouts/tile';

const styles = stylex.create({
  // Fluid auto-wrapping grid: fit as many ~11rem tiles as the container allows,
  // each growing to fill the row, wrapping to the next line when they no longer
  // fit. Replaces the fixed 12-column `span` layout.
  grid: {
    gridTemplateColumns: 'repeat(auto-fill, minmax(11rem, 1fr))',
  },
});

interface CustomFieldsProps {
  onSelected: (field: FormCustomField) => void;
}

export const CustomFields = ({ onSelected }: CustomFieldsProps) => {
  const counter = useRef(1);
  const nextName = () => `custom_${counter.current++}`;

  return (
    <LayoutGrid rowGap="5" columnGap="5" style={styles.grid}>
      <Tile
        title="Select"
        icon={<SelectComponentIcon />}
        onClick={() => {
          onSelected({
            type: 'select',
            name: nextName(),
            label: 'Custom',
            options: [{ value: 'Option 1' }, { value: 'Option 2' }],
          });
        }}
      />
      <Tile
        title="Text Field"
        icon={<FontIcon />}
        onClick={() => {
          onSelected({
            type: 'text',
            name: nextName(),
            label: 'Custom',
          });
        }}
      />
      <Tile
        title="Text Area"
        icon={<MenuIcon />}
        onClick={() => {
          onSelected({
            type: 'textarea',
            name: nextName(),
            label: 'Custom',
          });
        }}
      />
      <Tile
        title="Checkbox"
        icon={<TickIcon />}
        onClick={() => {
          onSelected({
            type: 'checkbox',
            name: nextName(),
            label: 'Custom',
          });
        }}
      />
      <Tile
        title="Radio Buttons"
        icon={<MoreIcon />}
        onClick={() => {
          onSelected({
            type: 'radio',
            name: nextName(),
            label: 'Custom',
            options: [{ value: 'Option 1' }, { value: 'Option 2' }],
          });
        }}
      />
    </LayoutGrid>
  );
};
