import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { onMounted } from 'vue';
import { UiIcon } from '@/components/UiIcon';
import { RouterLink, RouterView, useRouter } from 'vue-router';
import UiSidebar from './UiSidebar.vue';
import UiSidebarContent from './UiSidebarContent.vue';
import UiSidebarHeader from './UiSidebarHeader.vue';
import UiSidebarInset from './UiSidebarInset.vue';
import UiSidebarMenu from './UiSidebarMenu.vue';
import UiSidebarMenuButton from './UiSidebarMenuButton.vue';
import UiSidebarMenuItem from './UiSidebarMenuItem.vue';
import UiSidebarProvider from './UiSidebarProvider.vue';

const meta: Meta<typeof UiSidebarMenuItem> = {
  title: 'Patterns/UiSidebar/UiSidebarMenuItem',
  component: UiSidebarMenuItem,
  tags: ['autodocs'],
  parameters: {
    layout: 'padded',
    docs: {
      description: {
        component:
          'List item shell for the sidebar menu (`<li>`). Pass a `UiSidebarMenuButton` (or popover trigger) as the default slot. No pattern-specific props; `class` and other attributes forward to the primitive.',
      },
    },
  },
};

export default meta;

type Story = StoryObj<typeof UiSidebarMenuItem>;

export const Default: Story = {
  render: () => ({
    components: {
      UiIcon,
      UiSidebar,
      UiSidebarContent,
      UiSidebarHeader,
      UiSidebarMenu,
      UiSidebarMenuButton,
      UiSidebarMenuItem,
      UiSidebarProvider,
    },
    template: `
      <div class="bg-background-surface-primary p-4">
        <UiSidebarProvider :default-open="true">
          <UiSidebar collapsible="icon" class="w-72">
            <UiSidebarHeader tooltip="Toggle sidebar">Preview</UiSidebarHeader>
            <UiSidebarContent class="p-2">
              <UiSidebarMenu class="gap-y-1">
                <UiSidebarMenuItem>
                  <UiSidebarMenuButton tooltip="Overview">
                    <template #start-icon>
                      <UiIcon name="folder" size="s" />
                    </template>
                    Overview
                  </UiSidebarMenuButton>
                </UiSidebarMenuItem>

                <UiSidebarMenuItem>
                  <UiSidebarMenuButton tooltip="Settings" is-active>
                    <template #start-icon>
                      <UiIcon name="folder" size="s" />
                    </template>
                    Settings
                  </UiSidebarMenuButton>
                </UiSidebarMenuItem>
              </UiSidebarMenu>
            </UiSidebarContent>
          </UiSidebar>
        </UiSidebarProvider>
      </div>
    `,
  }),
};

/**
 * Each `UiSidebarMenuItem` hosts a `RouterLink` (in `custom` mode) that forwards
 * the router's `isActive` and `navigate` helpers to `UiSidebarMenuButton`:
 *
 * - `UiSidebarMenuButton` is rendered as `<a :href="href">` via the `as` + `href`
 *   attrs (forwarded to the core primitive), so middle-click and copy-link work.
 * - `@click="navigate"` delegates navigation back to Vue Router.
 * - `:is-active="isActive"` drives the active rail + token treatment from the
 *   current route, no manual state needed.
 *
 * The story registers three routes against the Storybook-level router (see
 * `.storybook/preview.ts`) and renders `<RouterView />` in a `UiSidebarInset`
 * panel so route changes are visible.
 */
export const WithVueRouter: Story = {
  parameters: {
    layout: 'fullscreen',
    docs: {
      description: {
        story:
          'Wire `UiSidebarMenuItem` + `UiSidebarMenuButton` to Vue Router using `<RouterLink custom>`. The button receives `href`, `isActive`, and `navigate` from the slot props and renders as an `<a>` tag for proper middle-click / open-in-new-tab semantics.',
      },
    },
  },
  render: () => ({
    components: {
      RouterLink,
      RouterView,
      UiIcon,
      UiSidebar,
      UiSidebarContent,
      UiSidebarHeader,
      UiSidebarInset,
      UiSidebarMenu,
      UiSidebarMenuButton,
      UiSidebarMenuItem,
      UiSidebarProvider,
    },
    setup() {
      const router = useRouter();

      const items = [
        { to: '/sidebar-demo/overview', label: 'Overview', icon: 'home' },
        { to: '/sidebar-demo/projects', label: 'Projects', icon: 'folder' },
        { to: '/sidebar-demo/settings', label: 'Settings', icon: 'settings' },
      ];

      for (const item of items) {
        if (!router.hasRoute(item.to)) {
          router.addRoute({
            path: item.to,
            name: item.to,
            component: {
              props: ['label'],
              setup: () => ({ label: item.label }),
              template: `
                <div class="flex flex-col gap-2 p-6">
                  <div class="label-12-regular text-content-on-surface-muted">Route</div>
                  <div class="heading-s text-content-on-surface-primary">{{ label }}</div>
                  <div class="body-14-regular text-content-on-surface-muted">
                    Rendered by <code>&lt;RouterView /&gt;</code> for <code>${item.to}</code>.
                  </div>
                </div>
              `,
            },
          });
        }
      }

      onMounted(() => {
        router.replace(items[0].to);
      });

      return { items };
    },
    template: `
      <UiSidebarProvider :default-open="true">
        <UiSidebar collapsible="icon" class="w-72">
          <UiSidebarHeader tooltip="Toggle sidebar">Navigation</UiSidebarHeader>
          <UiSidebarContent class="p-2">
            <UiSidebarMenu class="gap-y-1">
              <UiSidebarMenuItem v-for="item in items" :key="item.to">
                <RouterLink
                  :to="item.to"
                  custom
                  v-slot="{ href, isActive, navigate }"
                >
                  <UiSidebarMenuButton
                    as="a"
                    :href="href"
                    :tooltip="item.label"
                    :is-active="isActive"
                    @click="navigate"
                  >
                    <template #start-icon>
                      <UiIcon :name="item.icon" size="s" />
                    </template>
                    {{ item.label }}
                  </UiSidebarMenuButton>
                </RouterLink>
              </UiSidebarMenuItem>
            </UiSidebarMenu>
          </UiSidebarContent>
        </UiSidebar>

        <UiSidebarInset>
          <RouterView />
        </UiSidebarInset>
      </UiSidebarProvider>
    `,
  }),
};
