import { createListCollection, useListSelection } from '@ark-ui/solid/collection'
import { For } from 'solid-js'
import styles from 'styles/list-selection.module.css'

export const Multiple = () => {
  const collection = createListCollection({
    items: [
      { label: 'React', value: 'react' },
      { label: 'Vue', value: 'vue' },
      { label: 'Angular', value: 'angular' },
      { label: 'Svelte', value: 'svelte' },
      { label: 'Solid', value: 'solid' },
    ],
  })

  const selection = useListSelection({
    collection,
    selectionMode: 'multiple',
  })

  const handleSelectAll = () => {
    if (selection.isAllSelected()) {
      selection.clear()
    } else {
      selection.setSelectedValues(collection.getValues())
    }
  }

  return (
    <div class={styles.Root}>
      <div class={styles.Header}>
        <span class={styles.Count}>
          {selection.selectedValues().length} of {collection.items.length} selected
        </span>
        <button type="button" class={styles.SelectAllButton} onClick={handleSelectAll}>
          {selection.isAllSelected() ? 'Deselect all' : 'Select all'}
        </button>
      </div>
      <For each={collection.items}>
        {(item) => (
          <label class={styles.Item} data-selected={selection.isSelected(item.value) || undefined}>
            <input
              type="checkbox"
              class={styles.Checkbox}
              checked={selection.isSelected(item.value)}
              onChange={() => selection.select(item.value)}
            />
            <span class={styles.ItemText}>{item.label}</span>
          </label>
        )}
      </For>
    </div>
  )
}
