import {
  argsToTemplate,
  type Meta,
  type StoryObj,
  moduleMetadata,
} from '@storybook/angular';
import {
  UiSearchBarClearComponent,
  UiSearchBarComponent,
} from '@isa/ui/search-bar';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IconButtonComponent } from '@isa/ui/buttons';

type Appearance = 'main' | 'results';

export interface UiSearchBarComponentInputs {
  appearance: Appearance;
  placeholder: string;
  value: string;
  resetValue: string;
}

const meta: Meta<UiSearchBarComponentInputs> = {
  component: UiSearchBarComponent,
  decorators: [
    moduleMetadata({
      imports: [
        IconButtonComponent,
        UiSearchBarClearComponent,
        FormsModule,
        ReactiveFormsModule,
      ],
    }),
  ],
  title: 'ui/search-bar/SearchBar',
  argTypes: {
    placeholder: {
      control: 'text',
    },
    value: {
      control: 'text',
    },
    resetValue: {
      control: 'text',
    },
    appearance: {
      control: 'select',
      options: ['main', 'results'] as Appearance[],
      type: 'string',
    },
  },
  args: {
    placeholder: 'Rechnungsnummer, E-Mail, Kundenkarte, Name...',
    appearance: 'main',
  },
  render: (args) => {
    let button = '';

    if (args.appearance === 'main') {
      button =
        '<button type="submit" uiIconButton name="isaActionSearch" color="brand"></button>';
    } else if (args.appearance === 'results') {
      button =
        '<button type="submit" uiIconButton prefix name="isaActionSearch" color="neutral"></button>';
    }

    return {
      props: { ...args, control: new FormControl(args.value) },
      template: `<ui-search-bar appearance="${args.appearance}" ${argsToTemplate(args, { exclude: ['placeholder', 'value', 'resetValue', 'appearance'] })}>
            <input [formControl]="control" type="text" placeholder="${args.placeholder}" />
            <ui-search-bar-clear></ui-search-bar-clear>
            ${button}
            </ui-search-bar>
            `,
    };
  },
};

export default meta;

type Story = StoryObj<UiSearchBarComponent>;

export const Primary: Story = {
  args: {},
};
