import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { ref, onMounted, onUnmounted } from 'vue';
import UiKbd from './UiKbd.vue';
import UiKbdGroup from './UiKbdGroup.vue';
import { UiButton } from '../UiButton';
import {
  UiTooltipRoot,
  UiTooltipContent,
  UiTooltipProvider,
  UiTooltipTrigger,
} from '../UiTooltip';
import {
  UiDrawer,
  UiDrawerClose,
  UiDrawerContent,
  UiDrawerDescription,
  UiDrawerFooter,
  UiDrawerHeader,
  UiDrawerTitle,
} from '../UiDrawer';

/**
 * UiKbd renders a keyboard key or shortcut combination (e.g. `⌘ K`, `Ctrl + S`).
 * Use it inline with text or inside menus and tooltips to expose keyboard accelerators consistently.
 */
const meta: Meta<typeof UiKbd> = {
  title: 'Components/UiKbd',
  component: UiKbd,
  tags: ['autodocs'],
  argTypes: {
    size: {
      control: 'select',
      options: ['sm', 'default', 'lg'],
      description: 'Size variant for the kbd element',
    },
  },
  args: {
    size: 'default',
  },
};

export default meta;

type Story = StoryObj<typeof UiKbd>;

const defaultTemplateSource = `<script setup lang="ts">
import { UiKbd, UiKbdGroup } from '@aleph-alpha/ui-library'
</script>

<template>
  <div class="flex flex-col items-center gap-4">
    <UiKbdGroup>
      <UiKbd>⌘</UiKbd>
      <UiKbd>⇧</UiKbd>
      <UiKbd>⌥</UiKbd>
      <UiKbd>⌃</UiKbd>
    </UiKbdGroup>

    <UiKbdGroup>
      <UiKbd>Ctrl</UiKbd>
      <span>+</span>
      <UiKbd>B</UiKbd>
    </UiKbdGroup>
  </div>
</template>`;

/**
 * Default keyboard shortcut display with modifier symbols and key combinations.
 * Use the size control to change the kbd size.
 */
export const Default: Story = {
  render: (args) => ({
    components: { UiKbd, UiKbdGroup },
    setup() {
      return { args };
    },
    template: `
      <div class="flex flex-col items-center gap-4">
        <UiKbdGroup>
          <UiKbd v-bind="args">⌘</UiKbd>
          <UiKbd v-bind="args">⇧</UiKbd>
          <UiKbd v-bind="args">⌥</UiKbd>
          <UiKbd v-bind="args">⌃</UiKbd>
        </UiKbdGroup>

        <UiKbdGroup>
          <UiKbd v-bind="args">Ctrl</UiKbd>
          <span>+</span>
          <UiKbd v-bind="args">B</UiKbd>
        </UiKbdGroup>
      </div>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: defaultTemplateSource,
      },
    },
  },
};

const interactiveTemplateSource = `<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { UiKbd, UiKbdGroup, UiButton, UiDrawer, UiDrawerContent, UiDrawerHeader, UiDrawerTitle, UiDrawerDescription, UiDrawerFooter, UiDrawerClose } from '@aleph-alpha/ui-library'

const isDrawerOpen = ref(false)
const showHelp = ref(false)

const handleKeydown = (e: KeyboardEvent) => {
  if ((e.ctrlKey || e.metaKey) && e.key === '.') {
    e.preventDefault()
    isDrawerOpen.value = true
  }
  if ((e.ctrlKey || e.metaKey) && e.key === '/') {
    e.preventDefault()
    showHelp.value = !showHelp.value
  }
  if (e.key === 'Escape') {
    isDrawerOpen.value = false
    showHelp.value = false
  }
}

onMounted(() => window.addEventListener('keydown', handleKeydown))
onUnmounted(() => window.removeEventListener('keydown', handleKeydown))
</script>

<template>
  <div class="flex flex-col gap-3 rounded-lg border p-4">
    <div class="flex items-center justify-between gap-8">
      <span class="body-14-regular">Open Command Palette</span>
      <UiKbdGroup>
        <UiKbd>Ctrl</UiKbd>
        <span class="text-muted-foreground">+</span>
        <UiKbd>.</UiKbd>
      </UiKbdGroup>
    </div>
    <div class="flex items-center justify-between gap-8">
      <span class="body-14-regular">Toggle Help</span>
      <UiKbdGroup>
        <UiKbd>Ctrl</UiKbd>
        <span class="text-muted-foreground">+</span>
        <UiKbd>/</UiKbd>
      </UiKbdGroup>
    </div>
  </div>

  <UiDrawer v-model:open="isDrawerOpen">
    <UiDrawerContent>
      <UiDrawerHeader>
        <UiDrawerTitle>Command Palette</UiDrawerTitle>
        <UiDrawerDescription>
          Press <UiKbd size="sm">Esc</UiKbd> to close.
        </UiDrawerDescription>
      </UiDrawerHeader>
    </UiDrawerContent>
  </UiDrawer>
</template>`;

/**
 * Interactive keyboard shortcut demo. Press the keyboard shortcuts to trigger actions!
 * - Press `Ctrl/⌘ + .` to open the command palette drawer
 * - Press `Ctrl/⌘ + /` to toggle help
 */
export const Interactive: Story = {
  parameters: {
    docs: {
      source: {
        code: interactiveTemplateSource,
      },
    },
  },
  render: () => ({
    components: {
      UiKbd,
      UiKbdGroup,
      UiButton,
      UiDrawer,
      UiDrawerClose,
      UiDrawerContent,
      UiDrawerDescription,
      UiDrawerFooter,
      UiDrawerHeader,
      UiDrawerTitle,
    },
    setup() {
      const isDrawerOpen = ref(false);
      const showHelp = ref(false);
      const lastPressed = ref('');

      const handleKeydown = (e: KeyboardEvent) => {
        if ((e.ctrlKey || e.metaKey) && e.key === '.') {
          e.preventDefault();
          isDrawerOpen.value = true;
          lastPressed.value = 'Ctrl + .';
        }
        if ((e.ctrlKey || e.metaKey) && e.key === '/') {
          e.preventDefault();
          showHelp.value = !showHelp.value;
          lastPressed.value = 'Ctrl + /';
        }
        if (e.key === 'Escape') {
          isDrawerOpen.value = false;
          showHelp.value = false;
          lastPressed.value = 'Esc';
        }
      };

      onMounted(() => {
        window.addEventListener('keydown', handleKeydown);
      });

      onUnmounted(() => {
        window.removeEventListener('keydown', handleKeydown);
      });

      return { isDrawerOpen, showHelp, lastPressed };
    },
    template: `
      <div class="flex flex-col items-center gap-6 p-4">
        <div class="text-center gap-y-2">
          <h3 class="heading-s">Interactive Keyboard Shortcuts</h3>
          <p class="body-14-regular text-muted-foreground">Try pressing these keyboard shortcuts:</p>
        </div>

        <div class="flex flex-col gap-3 rounded-lg border p-4 bg-background-surface-muted/30">
          <div class="flex items-center justify-between gap-8">
            <span class="body-14-regular">Open Command Palette</span>
            <UiKbdGroup>
              <UiKbd>Ctrl</UiKbd>
              <span class="text-muted-foreground">+</span>
              <UiKbd>.</UiKbd>
            </UiKbdGroup>
          </div>
          <div class="flex items-center justify-between gap-8">
            <span class="body-14-regular">Toggle Help</span>
            <UiKbdGroup>
              <UiKbd>Ctrl</UiKbd>
              <span class="text-muted-foreground">+</span>
              <UiKbd>/</UiKbd>
            </UiKbdGroup>
          </div>
          <div class="flex items-center justify-between gap-8">
            <span class="body-14-regular">Close / Dismiss</span>
            <UiKbd>Esc</UiKbd>
          </div>
        </div>

        <div v-if="lastPressed" class="body-14-regular text-muted-foreground">
          Last pressed: <UiKbd>{{ lastPressed }}</UiKbd>
        </div>

        <div v-if="showHelp" class="w-full max-w-md rounded-lg border bg-card p-4 shadow-lg">
          <div class="flex items-center justify-between mb-3">
            <h4 class="body-14-medium">Keyboard Shortcuts Help</h4>
            <UiKbd>Esc</UiKbd>
          </div>
          <div class="gap-y-2 body-14-regular text-muted-foreground">
            <p>Use keyboard shortcuts to navigate quickly through the application.</p>
            <p>Press <UiKbd>Esc</UiKbd> to close this help panel.</p>
          </div>
        </div>

        <UiDrawer v-model:open="isDrawerOpen">
          <UiDrawerContent>
            <UiDrawerHeader>
              <UiDrawerTitle>Command Palette</UiDrawerTitle>
              <UiDrawerDescription>
                Quick access to common actions. Press <UiKbd size="sm">Esc</UiKbd> to close.
              </UiDrawerDescription>
            </UiDrawerHeader>
            <div class="p-4 gap-y-2">
              <div class="flex items-center justify-between rounded-md px-3 py-2 hover-layer hover-layer-default cursor-pointer">
                <span>New Document</span>
                <UiKbdGroup>
                  <UiKbd size="sm">Ctrl</UiKbd>
                  <UiKbd size="sm">N</UiKbd>
                </UiKbdGroup>
              </div>
              <div class="flex items-center justify-between rounded-md px-3 py-2 hover-layer hover-layer-default cursor-pointer">
                <span>Search Files</span>
                <UiKbdGroup>
                  <UiKbd size="sm">Ctrl</UiKbd>
                  <UiKbd size="sm">Shift</UiKbd>
                  <UiKbd size="sm">F</UiKbd>
                </UiKbdGroup>
              </div>
              <div class="flex items-center justify-between rounded-md px-3 py-2 hover-layer hover-layer-default cursor-pointer">
                <span>Go to Line</span>
                <UiKbdGroup>
                  <UiKbd size="sm">Ctrl</UiKbd>
                  <UiKbd size="sm">G</UiKbd>
                </UiKbdGroup>
              </div>
            </div>
            <UiDrawerFooter>
              <UiDrawerClose as-child>
                <UiButton variant="outline">Close</UiButton>
              </UiDrawerClose>
            </UiDrawerFooter>
          </UiDrawerContent>
        </UiDrawer>
      </div>
    `,
  }),
};

const groupTemplateSource = `<script setup lang="ts">
import { UiKbd, UiKbdGroup } from '@aleph-alpha/ui-library'
</script>

<template>
  <p class="body-14-regular text-muted-foreground">
    Use
    <UiKbdGroup>
      <UiKbd>Ctrl</UiKbd>
      <UiKbd>Shift</UiKbd>
      <UiKbd>P</UiKbd>
    </UiKbdGroup>
    to open the command palette
  </p>
</template>`;

/**
 * Use the `UiKbdGroup` component to group keyboard keys together.
 */
export const Group: Story = {
  render: (args) => ({
    components: { UiKbd, UiKbdGroup },
    setup() {
      return { args };
    },
    template: `
      <div class="flex flex-col items-center gap-4">
        <p class="body-14-regular text-muted-foreground">
          Use
          <UiKbdGroup>
            <UiKbd v-bind="args">Ctrl + Shift + P</UiKbd>
          </UiKbdGroup>
          to open the command palette
        </p>

        <div class="mt-8 w-full max-w-md rounded-lg border bg-background-surface-floating p-4 shadow-lg">
          <div class="flex items-center gap-2 border-b pb-3">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-muted-foreground"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
            <span class="flex-1 body-14-regular text-muted-foreground">Type a command or search...</span>
            <UiKbd v-bind="args">Esc</UiKbd>
          </div>
          <div class="pt-3 gap-y-1">
            <div class="flex items-center justify-between rounded-md px-2 py-1.5 body-14-regular hover-layer hover-layer-default cursor-pointer">
              <span>Toggle Sidebar</span>
              <UiKbdGroup>
                <UiKbd v-bind="args">Ctrl</UiKbd>
                <UiKbd v-bind="args">\\</UiKbd>
              </UiKbdGroup>
            </div>
            <div class="flex items-center justify-between rounded-md px-2 py-1.5 body-14-regular hover-layer hover-layer-default cursor-pointer">
              <span>Quick Search</span>
              <UiKbdGroup>
                <UiKbd v-bind="args">Ctrl</UiKbd>
                <UiKbd v-bind="args">Shift</UiKbd>
                <UiKbd v-bind="args">F</UiKbd>
              </UiKbdGroup>
            </div>
            <div class="flex items-center justify-between rounded-md px-2 py-1.5 body-14-regular hover-layer hover-layer-default cursor-pointer">
              <span>Go to Line</span>
              <UiKbdGroup>
                <UiKbd v-bind="args">Ctrl</UiKbd>
                <UiKbd v-bind="args">G</UiKbd>
              </UiKbdGroup>
            </div>
          </div>
        </div>
      </div>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: groupTemplateSource,
      },
    },
  },
};

const buttonTemplateSource = `<script setup lang="ts">
import { UiKbd, UiButton } from '@aleph-alpha/ui-library'
</script>

<template>
  <div class="flex flex-wrap items-center gap-4">
    <UiButton variant="outline" size="sm" class="pr-2">
      Accept <UiKbd>⏎</UiKbd>
    </UiButton>
    <UiButton variant="outline" size="sm" class="pr-2">
      Cancel <UiKbd>Esc</UiKbd>
    </UiButton>
  </div>
</template>`;

/**
 * Use the `UiKbd` component inside a button.
 */
export const Button: Story = {
  render: (args) => ({
    components: { UiKbd, UiButton },
    setup() {
      return { args };
    },
    template: `
      <div class="flex flex-wrap items-center gap-4">
        <UiButton variant="outline" size="sm" class="pr-2">
          Accept <UiKbd v-bind="args">⏎</UiKbd>
        </UiButton>
        <UiButton variant="outline" size="sm" class="pr-2">
          Cancel <UiKbd v-bind="args">Esc</UiKbd>
        </UiButton>
      </div>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: buttonTemplateSource,
      },
    },
  },
};

const withTooltipTemplateSource = `<script setup lang="ts">
import { UiKbd, UiKbdGroup, UiButton, UiTooltipRoot, UiTooltipContent, UiTooltipProvider, UiTooltipTrigger } from '@aleph-alpha/ui-library'
</script>

<template>
  <UiTooltipProvider>
    <UiTooltipRoot>
      <UiTooltipTrigger as-child>
        <UiButton size="sm" variant="outline">Save</UiButton>
      </UiTooltipTrigger>
      <UiTooltipContent>
        <div class="flex items-center gap-2">
          Save Changes <UiKbd>S</UiKbd>
        </div>
      </UiTooltipContent>
    </UiTooltipRoot>
  </UiTooltipProvider>
</template>`;

/**
 * Use the `UiKbd` component inside a tooltip.
 */
export const WithTooltip: Story = {
  render: (args) => ({
    components: {
      UiKbd,
      UiKbdGroup,
      UiButton,
      UiTooltipRoot,
      UiTooltipContent,
      UiTooltipProvider,
      UiTooltipTrigger,
    },
    setup() {
      return { args };
    },
    template: `
      <div class="flex flex-wrap gap-4">
        <UiTooltipProvider>
          <UiTooltipRoot>
            <UiTooltipTrigger as-child>
              <UiButton size="sm" variant="outline">Save</UiButton>
            </UiTooltipTrigger>
            <UiTooltipContent>
              <div class="flex items-center gap-2">
                Save Changes <UiKbd v-bind="args">S</UiKbd>
              </div>
            </UiTooltipContent>
          </UiTooltipRoot>
        </UiTooltipProvider>

        <UiTooltipProvider>
          <UiTooltipRoot>
            <UiTooltipTrigger as-child>
              <UiButton size="sm" variant="outline">Print</UiButton>
            </UiTooltipTrigger>
            <UiTooltipContent>
              <div class="flex items-center gap-2">
                Print Document
                <UiKbdGroup>
                  <UiKbd v-bind="args">Ctrl</UiKbd>
                  <UiKbd v-bind="args">P</UiKbd>
                </UiKbdGroup>
              </div>
            </UiTooltipContent>
          </UiTooltipRoot>
        </UiTooltipProvider>
      </div>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: withTooltipTemplateSource,
      },
    },
  },
};

const sizesTemplateSource = `<script setup lang="ts">
import { UiKbd } from '@aleph-alpha/ui-library'
</script>

<template>
  <div class="flex items-center gap-4">
    <UiKbd size="sm">Ctrl</UiKbd>
    <UiKbd>Ctrl</UiKbd>
    <UiKbd size="lg">Ctrl</UiKbd>
  </div>
</template>`;

/**
 * Different size variants.
 */
export const Sizes: Story = {
  render: () => ({
    components: { UiKbd },
    template: `
      <div class="flex items-center gap-4">
        <div class="flex items-center gap-1">
          <span class="text-xs text-muted-foreground">sm:</span>
          <UiKbd size="sm">Ctrl</UiKbd>
          <UiKbd size="sm">S</UiKbd>
        </div>
        <div class="flex items-center gap-1">
          <span class="text-xs text-muted-foreground">default:</span>
          <UiKbd>Ctrl</UiKbd>
          <UiKbd>S</UiKbd>
        </div>
        <div class="flex items-center gap-1">
          <span class="text-xs text-muted-foreground">lg:</span>
          <UiKbd size="lg">Ctrl</UiKbd>
          <UiKbd size="lg">S</UiKbd>
        </div>
      </div>
    `,
  }),
  parameters: {
    docs: {
      source: {
        code: sizesTemplateSource,
      },
    },
  },
};
