import { CommonModule, JsonPipe } from '@angular/common';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { argsToTemplate, Meta, moduleMetadata, StoryObj } from '@storybook/angular';
import { ButtonComponent, EngieTemplateDirective, SearchButtonDirective, SearchComponent } from '../../public-api';

/**
 * Search allows users to find the content they are looking for across an app or a website.
 * Basically, the input search allows users to input a query into a search text field to view related results.
 */
const meta: Meta<SearchComponent> = {
  title: 'Components/Search',
  id: 'search',
  component: SearchComponent,
  decorators: [
    moduleMetadata({
      imports: [
        CommonModule,
        ButtonComponent,
        SearchButtonDirective,
        EngieTemplateDirective,
        FormsModule,
        ReactiveFormsModule,
        JsonPipe
      ]
    })
  ],
  argTypes: {
    scale: {
      type: 'string',
      control: 'radio',
      options: ['sm', 'md', 'lg', 'xl']
    },
    enterKeydown: {
      control: {
        type: null
      }
    }
  },
  parameters: {
    docs: {
      imports: [SearchComponent, EngieTemplateDirective, SearchButtonDirective],
      since: '2.6.0'
    }
  }
};

export default meta;

type Story = StoryObj<SearchComponent>;

export const Default: Story = {
  name: 'Simple usage',
  args: {
    placeholder: 'Search'
  }
};

/**
 * You can use `EngieTemplateDirective` with `action` selector to place an action to the `SearchComponent`.
 *
 * Only a `ButtonComponent` with a `SearchButtonDirective` are handled by the `SearchComponent`
 */
export const WithButton: Story = {
  name: 'Add a button as action',
  args: {
    placeholder: 'Search'
  },
  render: (args) => ({
    props: args,
    template: `
    <nj-search ${argsToTemplate(args)}>
      <nj-button *njTemplate="'action'" njSearchButton>Search</nj-button>
    </nj-search>
    `
  })
};

/**
 * `SearchComponent` implements `ControlValueAccessor` interface. It can be interfaced with `FormsModule` and `ReactiveFormsModule` APIs
 */
export const WithAngularFormsAPI: Story = {
  name: 'Use core Angular forms APIs',
  args: {
    placeholder: 'Search'
  },
  render: (args) => ({
    props: {
      ...args,
      value: null,
      searchControl: new FormControl(),
      formControlState() {
        const { pristine, dirty, touched, untouched, value, status, errors } = this.searchControl;
        return { pristine, dirty, touched, untouched, value, status, errors };
      }
    },
    template: `
    <h3>With ngModel - FormsModule</h3>
    <p>
      <nj-search [(ngModel)]="value" ${argsToTemplate(args)}></nj-search>
    </p>
    <pre>Value: {{ value | json }}</pre>
    <hr>
    <h3>With FormControl - ReactiveFormsModule</h3>
    <p>
      <nj-search [formControl]="searchControl" ${argsToTemplate(args)}></nj-search>
    </p>
    <pre>Control: {{ formControlState() | json }}</pre>
    `
  })
};
