import { CaretSortIcon, CheckIcon } from '@radix-ui/react-icons'

import * as React from 'react'

import { Button } from '@components/ui/button/button'
import {
  CommandPalette,
  CommandPaletteEmpty,
  CommandPaletteGroup,
  CommandPaletteInput,
  CommandPaletteItem,
  CommandPaletteList,
} from '@components/ui/command-palette/command-palette'
import { Popover, PopoverContent, PopoverTrigger } from '@components/ui/popover/popover'
import { cn } from '@lib/utils'

const frameworks = [
  {
    value: 'next.js',
    label: 'Next.js',
  },
  {
    value: 'sveltekit',
    label: 'SvelteKit',
  },
  {
    value: 'nuxt.js',
    label: 'Nuxt.js',
  },
  {
    value: 'remix',
    label: 'Remix',
  },
  {
    value: 'astro',
    label: 'Astro',
  },
]

export function ComboboxDemo() {
  const [open, setOpen] = React.useState(false)
  const [value, setValue] = React.useState('')

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button variant="outline" aria-expanded={open} className="w-[200px] justify-between">
          {value ? frameworks.find((framework) => framework.value === value)?.label : 'Select framework...'}
          <CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[200px] p-0">
        <CommandPalette>
          <CommandPaletteInput placeholder="Search framework..." className="h-9" />
          <CommandPaletteList>
            <CommandPaletteEmpty>No framework found.</CommandPaletteEmpty>
            <CommandPaletteGroup>
              {frameworks.map((framework) => (
                <CommandPaletteItem
                  key={framework.value}
                  value={framework.value}
                  onSelect={(currentValue) => {
                    setValue(currentValue === value ? '' : currentValue)
                    setOpen(false)
                  }}
                >
                  {framework.label}
                  <CheckIcon
                    className={cn('ml-auto h-4 w-4', value === framework.value ? 'opacity-100' : 'opacity-0')}
                  />
                </CommandPaletteItem>
              ))}
            </CommandPaletteGroup>
          </CommandPaletteList>
        </CommandPalette>
      </PopoverContent>
    </Popover>
  )
}
