import type { Meta, StoryObj } from '@storybook/react-vite'
import { SunIcon, ChevronUpIcon, ChevronDownIcon } from '@radix-ui/react-icons'
import { expect, userEvent, screen, waitFor } from 'storybook/test'
import { useState } from 'react'
import {
  DropdownMenu,
  DropdownMenuPortal,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuLabel,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
} from './dropdown-menu'
import { Button } from '@components/ui/button/button'
import { Label } from '@components/ui/label/label'
import { Checkbox } from '@components/ui/checkbox/checkbox'
import { Input } from '@components/ui/input/input'

const meta = {
  title: 'DropdownMenu',
  component: DropdownMenu,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  argTypes: {},
} satisfies Meta<typeof DropdownMenu>
export default meta

type Story = StoryObj<typeof meta>

export const Default: Story = {
  render: () => (
    <div data-testid="outside-click-for-test" className="pointer-events-auto">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline">Open dropdown</Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent className="w-[250px]" align="start">
          <DropdownMenuLabel>Category 1</DropdownMenuLabel>
          <DropdownMenuGroup>
            <DropdownMenuItem>Item 1</DropdownMenuItem>
            <DropdownMenuItem>
              Item 2<DropdownMenuShortcut>⌘P (only visually)</DropdownMenuShortcut>
            </DropdownMenuItem>
          </DropdownMenuGroup>
          <DropdownMenuSeparator />
          <DropdownMenuGroup>
            <DropdownMenuSub>
              <DropdownMenuSubTrigger>Sub menu trigger</DropdownMenuSubTrigger>
              <DropdownMenuPortal>
                <DropdownMenuSubContent>
                  <DropdownMenuItem>Sub Item 1</DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem>More... (just another item)</DropdownMenuItem>
                </DropdownMenuSubContent>
              </DropdownMenuPortal>
            </DropdownMenuSub>
            <DropdownMenuItem disabled>Disabled</DropdownMenuItem>
            <div className="flex items-center justify-center gap-3 mt-5">
              <span>or just use custom content instead of the DropdownMenuItems</span>
              <SunIcon className="size-15 text-yellow-500" />
            </div>
          </DropdownMenuGroup>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  ),
  play: async () => {
    await userEvent.click(screen.getByText('Open dropdown'))
    const item1 = await screen.findByText('Item 1')
    await waitFor(() => {
      const style = window.getComputedStyle(item1)
      expect(style.visibility).toBe('visible')
      expect(Number(style.opacity)).toBeGreaterThan(0)
    })
    await userEvent.click(screen.getByTestId('outside-click-for-test'))
    await waitFor(() => {
      expect(screen.queryByText('Item 1')).toBeNull()
    })
    await userEvent.keyboard('{Escape}')
    await waitFor(() => {
      expect(screen.queryByText('Item 1')).toBeNull()
    })
  },
}

export const ExampleDropdownSearchableSelection: Story = {
  render: () => {
    const dummyUsers = [
      { id: '1', name: 'alice@wonderland.net' },
      { id: '2', name: 'bob.builder@kika.de' },
      { id: '3', name: 'charlie.bucket@chocolate-factory.com' },
    ]
    const [menuOpen, setMenuOpen] = useState(false)
    const [userFilterValue, setUserFilterValue] = useState('')
    const [selectedUserIds, setSelectedUserIds] = useState<string[]>([])

    const filteredUserData = dummyUsers.filter((user) =>
      user.name.toLowerCase().includes(userFilterValue.toLowerCase()),
    )

    const handleCheckboxChange = (userId: string) => {
      setSelectedUserIds((prev) => (prev.includes(userId) ? prev.filter((id) => id !== userId) : [...prev, userId]))
    }

    return (
      <div className="w-[180px]">
        <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
          <DropdownMenuTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              className="group w-full flex items-center justify-between disabled:text-muted-foreground border-input hover:bg-muted-foreground hover:text-background"
            >
              <span className="mx-auto">
                {selectedUserIds.length === 0
                  ? 'Select specific users'
                  : `${selectedUserIds.length} user${selectedUserIds.length > 1 ? 's' : ''} selected`}
              </span>
              {menuOpen ? (
                <ChevronUpIcon className="size-4 opacity-50 text-muted-foreground group-hover:text-background" />
              ) : (
                <ChevronDownIcon className="size-4 opacity-50 group-hover:opacity-100 text-muted-foreground group-hover:text-background" />
              )}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-[280px] flex flex-col p-0 border-(--discreet-border)">
            <Input
              className=" rounded-none border-0 border-b-1"
              variant="simple"
              placeholder="Search users"
              value={userFilterValue}
              onChange={(e) => setUserFilterValue(e.target.value)}
            />
            <div className="p-1">
              {filteredUserData.length > 0 ? (
                filteredUserData.map((user) => (
                  <div key={user.id} className="flex hover:bg-accent py-1 px-2 rounded items-center gap-2">
                    <Checkbox
                      checked={selectedUserIds.includes(user.id)}
                      onChange={() => handleCheckboxChange(user.id)}
                      id={`user-${user.id}`}
                      variant="iconSolo"
                      checkboxSize="lg"
                      checkIcon="check"
                      iconStyle="solo"
                    />
                    <Label htmlFor={`user-${user.id}`} className="cursor-pointer">
                      {user.name}
                    </Label>
                  </div>
                ))
              ) : (
                <p className="text-center text-muted-foreground py-3">no results found</p>
              )}
            </div>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    )
  },
}
