import type { Meta, StoryObj } from '@storybook/react';
import { Search } from '@transferwise/icons';
import { useRef, useState } from 'react';

import ActionButton from '../actionButton';
import { Field } from '../field/Field';

import { Input } from './Input';
import { InputGroup } from './InputGroup';

export default {
  component: InputGroup,
  title: 'Forms/InputGroup',
} satisfies Meta<typeof InputGroup>;

type Story = StoryObj<typeof InputGroup>;

export const WithPrefix: Story = {
  render: (args) => <InputGroupWithPrefix {...args} />,
  args: {
    disabled: false,
  },
};

function InputGroupWithPrefix(args: NonNullable<Story['args']>) {
  return (
    <InputGroup
      {...args}
      addonStart={{
        content: <Search size={24} />,
        initialContentWidth: 24,
      }}
    >
      <Input placeholder="Search by name…" />
    </InputGroup>
  );
}

export const WithSuffix: Story = {
  render: (args) => <InputGroupWithSuffix {...args} />,
  args: {
    disabled: false,
  },
  decorators: [
    (Story) => (
      <Field label="Label">
        <Story />
      </Field>
    ),
  ],
};

function InputGroupWithSuffix(args: NonNullable<Story['args']>) {
  const ref = useRef<HTMLInputElement>(null);
  const [value, setValue] = useState('Text value');

  return (
    <InputGroup
      {...args}
      addonEnd={{
        content: (
          <ActionButton
            onClick={async () => {
              await navigator.clipboard.writeText(value);
              if (ref.current != null) {
                ref.current.focus({ preventScroll: true });
                ref.current.select();
              }
            }}
          >
            Copy
          </ActionButton>
        ),
        interactive: true,
        padding: 'sm',
      }}
    >
      <Input ref={ref} value={value} onChange={(event) => setValue(event.currentTarget.value)} />
    </InputGroup>
  );
}
