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

import { Button } from '..';
import { Field } from '../field/Field';

import { Input } from './Input';
import { Flag } from '@wise/art';
import { InputGroup } from './InputGroup';
import AvatarView from '../avatarView';
import PhoneNumberInput from '../phoneNumberInput';

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: (
          <Button
            size="sm"
            v2
            onClick={async () => {
              await navigator.clipboard.writeText(value);
              if (ref.current != null) {
                ref.current.focus({ preventScroll: true });
                ref.current.select();
              }
            }}
          >
            Copy
          </Button>
        ),
        interactive: true,
        padding: 'sm',
      }}
    >
      <Input ref={ref} value={value} onChange={(event) => setValue(event.currentTarget.value)} />
    </InputGroup>
  );
}

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

function PhoneNumberInputGroupWithPrefix(args: NonNullable<Story['args']>) {
  return (
    <InputGroup
      {...args}
      addonStart={{
        content: (
          <AvatarView size={24}>
            <Flag code="gbp" />
          </AvatarView>
        ),
      }}
    >
      <PhoneNumberInput onChange={() => {}} />
    </InputGroup>
  );
}
