import { useEffect, useState } from 'react';
import { Meta, StoryObj } from '@storybook/react-webpack5';

import { Field } from '../field/Field';
import { Sentiment } from '../common';
import { TextArea } from './TextArea';

/**
 * TextArea must be the only input with `maxLength` inside a given Field.
 * The character counter uses shared context — multiple TextAreas with maxLength
 * in the same Field will race to set the counter state.
 */
const meta: Meta<typeof TextArea> = {
  title: 'Forms/TextArea',
  component: TextArea,
  argTypes: {
    value: {
      control: 'text',
    },
    maxLength: {
      control: 'number',
    },
    placeholder: {
      control: 'text',
    },
    disabled: {
      control: 'boolean',
    },
    rows: {
      control: 'number',
    },
  },
};

export default meta;
type Story = StoryObj<typeof TextArea>;

/** Explore all props via the controls panel. */
export const Playground: Story = {
  args: {
    value: '',
    maxLength: 200,
    placeholder: 'Type something...',
  },
  render: (args) => {
    const [value, setValue] = useState(args.value ?? '');
    useEffect(() => setValue(args.value ?? ''), [args.value]);

    return (
      <Field label="Message" required={false}>
        <TextArea {...args} value={value} onChange={({ target }) => setValue(target.value)} />
      </Field>
    );
  },
};

export const Basic: Story = {
  render: () => {
    const [value, setValue] = useState('');

    return (
      <Field label="Message" required={false}>
        <TextArea maxLength={200} value={value} onChange={({ target }) => setValue(target.value)} />
      </Field>
    );
  },
  parameters: {
    docs: {
      source: {
        code: `<Field label="Message" required={false}>
  <TextArea
    maxLength={200}
    value={value}
    onChange={({ target }) => setValue(target.value)}
  />
</Field>`,
      },
    },
  },
};

export const WithError: Story = {
  render: () => {
    const [value, setValue] = useState('');

    return (
      <Field
        label="Message"
        required={false}
        sentiment={Sentiment.NEGATIVE}
        message="You have exceeded the character limit"
      >
        <TextArea maxLength={200} value={value} onChange={({ target }) => setValue(target.value)} />
      </Field>
    );
  },
};
