import CodeSelect, { type ParameterInputValue } from '@/components/CodeSelect';
import { action } from '@storybook/addon-actions';
import { useArgs } from '@storybook/preview-api';
import type { Meta, StoryObj } from '@storybook/react';
import { fn } from '@storybook/test';
import { Button, Col, Form, Row } from 'antd';
import { http, HttpResponse } from 'msw';
import { codeListData } from './mockData';

// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
  title: 'Components/CodeSelect 代码配置选择器',
  component: CodeSelect,
  parameters: {
    // Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
    // layout: 'centered',
    msw: {
      handlers: [
        http.get('/api/mmp/codeConfig', () => {
          return HttpResponse.json(codeListData);
        }),
      ],
    },
  },
  // This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
  tags: ['autodocs'],
  // More on argTypes: https://storybook.js.org/docs/api/argtypes
  argTypes: {
    // backgroundColor: { control: 'color' },
  },
  // Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
  args: { onChange: fn() },
} satisfies Meta<typeof CodeSelect>;

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

// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary: Story = {
  args: {
    canInput: false,
    textArea: false,
    size: 'large',
    placeholder: '请选择代码配置',
    style: { width: 400 },
  },
  render: function Render(args) {
    const [{ value }, updateArgs] = useArgs();
    function handleChange(value?: ParameterInputValue) {
      updateArgs({ value: value });
      args.onChange?.(value);
    }

    return <CodeSelect {...args} value={value} onChange={handleChange}></CodeSelect>;
  },
};

export const InForm: Story = {
  render: ({ onChange }) => {
    return (
      <Form
        name="code-select-form"
        labelCol={{ flex: '80px' }}
        labelAlign="left"
        size="large"
        autoComplete="off"
        onFinish={action('onFinish')}
      >
        <Row gutter={8}>
          <Col span={10}>
            <Form.Item label="代码配置" name="code_config">
              <CodeSelect
                placeholder="请选择代码配置"
                canInput={false}
                size="large"
                onChange={onChange}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={8}>
          <Button htmlType="submit" type="primary">
            提交
          </Button>
        </Row>
      </Form>
    );
  },
};
