import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { ref } from 'vue';
import { UiIcon } from '@/components/UiIcon';
import Popover from '../../components/core/popover/Popover.vue';
import PopoverContent from '../../components/core/popover/PopoverContent.vue';
import PopoverTrigger from '../../components/core/popover/PopoverTrigger.vue';
import UiSidebar from './UiSidebar.vue';
import UiSidebarContent from './UiSidebarContent.vue';
import UiSidebarFooter from './UiSidebarFooter.vue';
import UiSidebarGroup from './UiSidebarGroup.vue';
import UiSidebarGroupContent from './UiSidebarGroupContent.vue';
import UiSidebarGroupLabel from './UiSidebarGroupLabel.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 UiSidebarPopoverMenu from './UiSidebarPopoverMenu.vue';
import UiSidebarPopoverMenuItem from './UiSidebarPopoverMenuItem.vue';
import UiSidebarProvider from './UiSidebarProvider.vue';
import UiSidebarRail from './UiSidebarRail.vue';

const meta: Meta<typeof UiSidebar> = {
  title: 'Patterns/UiSidebar/UiSidebar',
  component: UiSidebar,
  tags: ['autodocs'],
  args: {
    side: 'left',
    variant: 'sidebar',
    collapsible: 'icon',
    resizable: false,
    minWidth: 240,
    maxWidth: 480,
    defaultWidth: 256,
  },
  parameters: {
    layout: 'fullscreen',
    docs: {
      description: {
        component:
          'Application sidebar shell wrapping the core `Sidebar` primitive. Use with `UiSidebarProvider` as an ancestor; pair with `UiSidebarInset` for the main content column. Controls adjust `side`, `variant`, and `collapsible` for the demo layout.',
      },
    },
  },
  argTypes: {
    side: {
      control: 'select',
      options: ['left', 'right'],
      description: 'Which horizontal edge the sidebar is anchored to.',
    },
    variant: {
      control: 'select',
      options: ['sidebar', 'floating', 'inset'],
      description:
        'Layout style: standard rail, floating panel, or inset (main surface peers with gap/radius).',
    },
    collapsible: {
      control: 'select',
      options: ['offcanvas', 'icon', 'none'],
      description:
        'Collapse behavior: slide off-canvas, collapse to icon width, or non-collapsing.',
    },
    resizable: {
      control: 'boolean',
      description:
        'Allows resizing the desktop sidebar by dragging its outer border.',
    },
    minWidth: {
      control: { type: 'number', min: 160, max: 480, step: 8 },
      description: 'Minimum resizable sidebar width in pixels.',
    },
    maxWidth: {
      control: { type: 'number', min: 240, max: 720, step: 8 },
      description: 'Maximum resizable sidebar width in pixels.',
    },
    defaultWidth: {
      control: { type: 'number', min: 160, max: 720, step: 8 },
      description:
        'Initial sidebar width in pixels when no persisted width exists.',
    },
  },
};

export default meta;

type Story = StoryObj<typeof UiSidebar>;

const renderStory = (args: Story['args']) => ({
  components: {
    Popover,
    PopoverContent,
    PopoverTrigger,
    UiIcon,
    UiSidebar,
    UiSidebarContent,
    UiSidebarFooter,
    UiSidebarGroup,
    UiSidebarGroupContent,
    UiSidebarGroupLabel,
    UiSidebarHeader,
    UiSidebarInset,
    UiSidebarMenu,
    UiSidebarMenuButton,
    UiSidebarMenuItem,
    UiSidebarPopoverMenu,
    UiSidebarPopoverMenuItem,
    UiSidebarProvider,
    UiSidebarRail,
  },
  setup() {
    const primaryItems = [
      { title: 'Home', icon: 'home' },
      { title: 'Collections', icon: 'folder' },
      { title: 'Chat', icon: 'message-square' },
    ];

    const agentItems = ref([
      { title: 'Design engineering', icon: 'bot' },
      { title: 'Invoice generator', icon: 'file-text' },
    ]);

    const appItems = ref([
      { title: 'Translation', icon: 'languages' },
      { title: 'Transcription', icon: 'mic' },
    ]);

    type MenuSelection = { kind: 'menu'; title: string; icon: string };
    const selected = ref<MenuSelection>({
      kind: 'menu',
      title: primaryItems[0].title,
      icon: primaryItems[0].icon,
    });

    function selectMenu(item: { title: string; icon: string }) {
      selected.value = { kind: 'menu', title: item.title, icon: item.icon };
    }

    const isMenuActive = (title: string) =>
      selected.value.kind === 'menu' && selected.value.title === title;

    function addAgentItem() {
      const next = agentItems.value.length + 1;
      agentItems.value.push({
        title: 'Agent ' + next,
        icon: 'bot',
      });
    }

    function addAppItem() {
      const next = appItems.value.length + 1;
      appItems.value.push({
        title: 'App ' + next,
        icon: 'folder',
      });
    }

    return {
      addAgentItem,
      addAppItem,
      agentItems,
      appItems,
      args,
      isMenuActive,
      primaryItems,
      selected,
      selectMenu,
    };
  },
  template: `
    <UiSidebarProvider :default-open="true">
      <UiSidebar
        :side="args.side"
        :variant="args.variant"
        :collapsible="args.collapsible"
        :resizable="args.resizable"
        :default-width="args.defaultWidth"
        :min-width="args.minWidth"
        :max-width="args.maxWidth"
      >
        <UiSidebarHeader tooltip="Assistant" aria-label="Assistant sidebar trigger">
          <template #logo>
            <svg
              class="w-6"
              viewBox="0 0 20 20"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              aria-hidden="true"
            >
              <path d="M5.51166 16.0373L7.01104 17.9999C7.76073 17.4953 8.41178 16.8598 9.00364 16.1869L7.01104 14.6915C6.55728 15.1962 6.06406 15.6448 5.51166 16.0373Z" fill="#1D1D1B"/>
              <path d="M14.5278 3.96262L13.0284 2C12.2787 2.50467 11.6277 3.14019 11.0358 3.81308L13.0284 5.30841C13.4822 4.80374 13.9557 4.35514 14.5278 3.96262Z" fill="#1D1D1B"/>
              <path d="M11.2725 9.98131C11.2725 6.84112 9.65475 3.86916 6.97164 2L5.4328 3.96262C7.50432 5.38318 8.7275 7.64486 8.7275 10.0187C8.7275 13.1589 10.3453 16.1308 13.0284 18L14.5672 16.0374C12.5154 14.5981 11.2725 12.3551 11.2725 9.98131Z" fill="#1D1D1B"/>
              <path d="M3.04562 4.80371L2 7.00932C3.20345 7.53268 4.05179 8.67287 4.05179 9.99997C4.05179 11.3271 3.20345 12.486 2 12.9906L3.04562 15.1962C5.13687 14.299 6.59679 12.3177 6.59679 9.99997C6.59679 7.68222 5.13687 5.68222 3.04562 4.80371Z" fill="#1D1D1B"/>
              <path d="M15.9482 9.99997C15.9482 8.65418 16.7965 7.51399 18 7.00932L16.9544 4.80371C14.8631 5.70091 13.4032 7.70091 13.4032 9.99997C13.4032 12.3177 14.8631 14.299 16.9544 15.1962L18 12.9906C16.7768 12.486 15.9482 11.3271 15.9482 9.99997Z" fill="#1D1D1B"/>
            </svg>
          </template>
          Assistant
        </UiSidebarHeader>

        <UiSidebarContent>
          <UiSidebarMenu class="px-2 pt-1">
            <UiSidebarMenuItem v-for="item in primaryItems" :key="item.title">
              <UiSidebarMenuButton
                :tooltip="item.title"
                :is-active="isMenuActive(item.title)"
                @click="selectMenu(item)"
              >
                <template #start-icon>
                  <UiIcon :name="item.icon" size="s" />
                </template>
                {{ item.title }}
              </UiSidebarMenuButton>
            </UiSidebarMenuItem>
          </UiSidebarMenu>

          <UiSidebarGroup :default-open="true">
            <UiSidebarGroupLabel
              size="xs"
              collapse-tooltip="Toggle agents"
              action-tooltip="Add agent"
              @action-click="addAgentItem"
            >
              Agents
            </UiSidebarGroupLabel>
            <UiSidebarGroupContent>
              <UiSidebarMenu>
                <UiSidebarMenuItem v-for="item in agentItems" :key="item.title">
                  <UiSidebarMenuButton
                    :tooltip="item.title"
                    :is-active="isMenuActive(item.title)"
                    @click="selectMenu(item)"
                  >
                    <template #start-icon>
                      <UiIcon :name="item.icon" size="s" />
                    </template>
                    {{ item.title }}
                  </UiSidebarMenuButton>
                </UiSidebarMenuItem>
              </UiSidebarMenu>
            </UiSidebarGroupContent>
          </UiSidebarGroup>

          <UiSidebarGroup :default-open="true">
            <UiSidebarGroupLabel
              size="xs"
              collapse-tooltip="Toggle apps"
              action-tooltip="Add app"
              @action-click="addAppItem"
            >
              Apps
            </UiSidebarGroupLabel>
            <UiSidebarGroupContent>
              <UiSidebarMenu>
                <UiSidebarMenuItem v-for="item in appItems" :key="item.title">
                  <UiSidebarMenuButton
                    :tooltip="item.title"
                    :is-active="isMenuActive(item.title)"
                    @click="selectMenu(item)"
                  >
                    <template #start-icon>
                      <UiIcon :name="item.icon" size="s" />
                    </template>
                    {{ item.title }}
                  </UiSidebarMenuButton>
                </UiSidebarMenuItem>
              </UiSidebarMenu>
            </UiSidebarGroupContent>
          </UiSidebarGroup>
        </UiSidebarContent>

        <UiSidebarFooter>
          <Popover>
            <PopoverTrigger as-child>
              <UiSidebarMenuButton tooltip="Profile menu">
                <template #start-icon>
                  <div
                    class="flex size-8 items-center justify-center overflow-hidden rounded-md bg-background-surface-muted body-14-regular text-content-on-surface-primary"
                  >
                    U
                  </div>
                </template>
                user
                <template #subtitle>
                  descriptipn
                </template>
              </UiSidebarMenuButton>
            </PopoverTrigger>

            <PopoverContent side="top" align="start" :side-offset="8" class="w-[22rem] rounded-md p-0 shadow-md bg-background-surface-secondary">
              <UiSidebarPopoverMenu :show-footer-separator="true">
                <div class="flex items-center gap-3 px-2 py-2">
                  <div
                    class="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md bg-background-surface-muted body-14-regular text-content-on-surface-primary"
                  >
                    U
                  </div>
                  <div class="min-w-0">
                    <div class="truncate body-14-medium text-content-on-surface-primary">
                      user
                    </div>
                    <div class="truncate body-14-regular text-content-on-surface-muted">
                      descriptipn
                    </div>
                  </div>
                </div>

                <div class="mx-2 border-t border-border-surface-default"></div>

                <UiSidebarPopoverMenuItem label="Upgrade to Pro">
                  <template #icon>
                    <UiIcon name="sparkles" size="s" />
                  </template>
                </UiSidebarPopoverMenuItem>
                <UiSidebarPopoverMenuItem label="Account">
                  <template #icon>
                    <UiIcon name="user-circle" size="s" />
                  </template>
                </UiSidebarPopoverMenuItem>
                <UiSidebarPopoverMenuItem label="Billing">
                  <template #icon>
                    <UiIcon name="credit-card" size="s" />
                  </template>
                </UiSidebarPopoverMenuItem>
                <UiSidebarPopoverMenuItem label="Notifications">
                  <template #icon>
                    <UiIcon name="bell" size="s" />
                  </template>
                </UiSidebarPopoverMenuItem>

                <template #footer>
                  <UiSidebarPopoverMenuItem label="Log out">
                    <template #icon>
                      <UiIcon name="log-out" size="s" />
                    </template>
                  </UiSidebarPopoverMenuItem>
                </template>
              </UiSidebarPopoverMenu>
            </PopoverContent>
          </Popover>
        </UiSidebarFooter>

        <UiSidebarRail />
      </UiSidebar>

      <UiSidebarInset>
        <header class="flex h-14 items-center gap-2 border-b border-border-surface-default px-4">
          <span class="body-14-regular text-content-on-surface-primary">
            {{ selected.title }}
          </span>
        </header>
        <div class="flex min-h-[320px] flex-1 p-4">
          <div
            class="min-h-[540px] w-full rounded-md border border-border-surface-default bg-background-surface-primary p-6"
          >
            <div class="flex items-center gap-3 mb-4">
              <div
                class="flex size-10 items-center justify-center rounded-md border border-border-surface-default bg-background-surface-secondary text-content-on-surface-primary"
              >
                <UiIcon :name="selected.icon" :size="18" />
              </div>
              <div>
                <div class="heading-s text-content-on-surface-primary">{{ selected.title }}</div>
                <div class="body-14-regular text-content-on-surface-muted">
                  {{ selected.title }} screen
                </div>
              </div>
            </div>
            <div class="grid grid-cols-3 gap-3">
              <div
                v-for="n in 6"
                :key="n"
                class="h-20 rounded-md border border-border-surface-default bg-background-surface-secondary"
              />
            </div>
          </div>
        </div>
      </UiSidebarInset>
    </UiSidebarProvider>
  `,
});

export const Default: Story = {
  render: renderStory,
};

export const Resizable: Story = {
  render: renderStory,
  args: {
    resizable: true,
    collapsible: 'icon',
    defaultWidth: 280,
    minWidth: 240,
    maxWidth: 480,
  },
};

export const Inset: Story = {
  args: {
    variant: 'inset',
    collapsible: 'icon',
  },
  render: renderStory,
};

export const RightSide: Story = {
  args: {
    side: 'right',
    variant: 'sidebar',
    collapsible: 'offcanvas',
  },
  render: renderStory,
};
