import type { Meta, StoryObj } from '@storybook/angular';
import { moduleMetadata } from '@storybook/angular';
import type { Resource } from '@angular/core';
import { ASYNC } from './async.component';
import { SkeletonComponent } from '@shared/ui/skeleton/skeleton.component';

/** Minimal fake of a signal Resource so the wrapper can be driven through every
    state in isolation (no HTTP). */
function fakeResource<T>(status: string, value?: T, error?: Error): Resource<T> {
  return {
    value: () => value as T,
    status: () => status,
    error: () => error,
    hasValue: () => value !== undefined,
    reload: () => {},
  } as unknown as Resource<T>;
}

const meta: Meta = {
  title: 'Molecules/Async States',
  decorators: [moduleMetadata({ imports: [...ASYNC, SkeletonComponent] })],
  render: (args) => ({
    // isEmpty is a function — Storybook strips function args, so set it here.
    props: { ...args, isEmpty: (v: string[]) => !v || v.length === 0 },
    template: `
      <app-async [resource]="resource" [isEmpty]="isEmpty">
        <ng-template appAsyncLoaded let-items>
          <ul class="rhc-unordered-list">
            @for (i of items; track i) { <li>{{ i }}</li> }
          </ul>
        </ng-template>
        <ng-template appAsyncLoading><app-skeleton [count]="3" height="1.5rem" [delay]="0" /></ng-template>
        <ng-template appAsyncEmpty><p class="rhc-paragraph">Geen items gevonden.</p></ng-template>
      </app-async>`,
  }),
};
export default meta;
type Story = StoryObj;

export const Loaded: Story = { args: { resource: fakeResource('resolved', ['Huisartsgeneeskunde', 'Spoedeisende hulp']) } };
export const Loading: Story = { args: { resource: fakeResource('loading') } };
export const Empty: Story = { args: { resource: fakeResource('resolved', [] as string[]) } };
export const ErrorState: Story = { args: { resource: fakeResource('error', undefined, new Error('Demo')) } };
