import { APP_BASE_HREF } from '@angular/common';
import { Component } from '@angular/core';
import { provideRouter, RouterLink, RouterOutlet, Routes, withHashLocation } from '@angular/router';
import { applicationConfig, argsToTemplate, Meta, moduleMetadata, StoryObj } from '@storybook/angular';
import { withContrastedVariant } from '../../../.storybook/utils/with-contrasted-variant.decorator';
import { LinkComponent } from '../../public-api';

@Component({ template: 'One', selector: 'app-one' })
class OneComponent {}

@Component({ template: 'Two', selector: 'app-two' })
class TwoComponent {}

@Component({ template: 'Three', selector: 'app-three' })
class ThreeComponent {}

const routes: Routes = [
  { path: 'one', component: OneComponent },
  { path: 'two', component: TwoComponent },
  { path: 'three', component: ThreeComponent },
  { path: '**', redirectTo: '/one', pathMatch: undefined }
];

type LinkWithLabel = LinkComponent & { label?: string };

const meta: Meta<LinkWithLabel> = {
  title: 'Components/Link',
  id: 'link',
  component: LinkComponent,
  argTypes: {
    label: {
      description:
        'Note that this is not an `@Input()`, it should be placed inside `<nj-link>`. This can be any custom content'
    }
  },
  decorators: [
    applicationConfig({
      providers: [
        provideRouter(routes, withHashLocation()),
        {
          provide: APP_BASE_HREF,
          useValue: '/'
        }
      ]
    }),
    moduleMetadata({
      imports: [RouterLink, RouterOutlet]
    }),
    withContrastedVariant({
      stateByProps: (props) => {
        return props['variant'] === 'inverse' ? 'inverse' : props['variant'] === 'high-contrast' ? 'contrasted' : null;
      }
    })
  ],
  parameters: {
    docs: {
      imports: [LinkComponent]
    }
  }
};

export default meta;

type Story = StoryObj<LinkWithLabel>;

export const Link: Story = {
  args: {
    label: 'Link',
    externalLabel: '(open in new tab)'
  },
  render: (args) => ({
    props: args,
    template: `
      <nj-link ${argsToTemplate(args, { exclude: ['label'] })}>
          {{label}}
      </nj-link>
    `
  })
};

/**
 * `LinkComponent` can be interfaced with `RouterModule` API
 */
export const WithRouterLink: Story = {
  name: 'Use core Angular router API',
  render: (args) => ({
    props: args,
    template: `
      <div style="display: flex; gap: var(--nj-semantic-size-spacing-16)">
        <nj-link routerLink="one" ${argsToTemplate(args)}>
            One
        </nj-link>
        <nj-link routerLink="two" ${argsToTemplate(args)}>
            Two
        </nj-link>
        <nj-link routerLink="three" ${argsToTemplate(args)}>
            Three
        </nj-link>
      </div>
      <div style="display: flex; flex-direction: column">
        <h3>Current Route</h3>
        <router-outlet></router-outlet>
      </div>
    `
  })
};
