import type { Meta, StoryObj } from '@storybook/react';
import InputWithDropdown from './InputWithDropdown';
import { ChangeEvent, useState } from 'react';
import { Option } from './types';

const meta: Meta<typeof InputWithDropdown> = {
  title: 'Components/InputWithDropdown',
  component: InputWithDropdown,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
};

type Story = StoryObj<typeof InputWithDropdown>;

let optionsList = [
  { label: 'option 1', value: 'option 1' },
  { label: 'option 2', value: 'option 2' },
  { label: 'option 3', value: 'option 3' },
  { label: 'option 4', value: 'option 4' },
];
let selectedOption = { label: 'option 2', value: 'option 2' };

const defaultArgs = {
  label: 'Field-Name',
  disabled: false,
  placeholder: 'Enter your name',
  optionsList: optionsList,
  selectedOption: selectedOption,
};

export const Default: Story = {
  args: {
    ...defaultArgs,
    disabled: false,
    required: false,
  },
};

export const DisabledWithValue: Story = {
  args: {
    ...defaultArgs,
    variant: 'primary',
    type: 'text',
    value: 'Disabled',
    disabled: true,
    required: true,
  },
};

export const Controlled: Story = {
  render: () => {
    const [value, setValue] = useState<string>('');
    const [error, setError] = useState<boolean>(false);
    const [helperText, setHelperText] = useState<string>('');

    const optionsListToPass = [
      { label: 'milliseconds', value: 'milliseconds' },
      { label: 'seconds', value: 'seconds' },
      { label: 'minutes', value: 'minutes' },
      { label: 'hours', value: 'hours' },
    ];

    const [selectedOption, setSelectedOption] = useState<Option>({
      label: 'milliseconds',
      value: 'milliseconds',
    });

    const onDropdownChangeHandler = (option: Option) => {
      setSelectedOption(option);
      setValue('0');
    };

    const onInputChangeHandler = (event: ChangeEvent<HTMLInputElement>) => {
      const inputValue = event.target.value;
      setValue(inputValue);

      // Validation logic
      if (event.target) {
        if (inputValue.length <= 0) {
          setError(true);
          setHelperText(`${event.target.name} is required`);
        } else if (inputValue.length > 4) {
          setError(true);
          setHelperText(`${event.target.name} should be upto 999`);
        } else {
          setError(false);
          setHelperText('');
        }
      }
    };

    return (
      <InputWithDropdown
        {...defaultArgs}
        name="ImplicitTime"
        label="ImplicitTime"
        placeholder={`Enter ImplicitTime here`}
        value={value}
        type="number"
        required={true}
        error={error}
        helperText={helperText}
        optionsList={optionsListToPass}
        selectedOption={selectedOption}
        onInputChangeHandler={onInputChangeHandler}
        onDropdownChangeHandler={onDropdownChangeHandler}
      />
    );
  },
};

export default meta;
