import { useQuery } from '@based/react'
import { useMemo } from 'react'
import { Sheet } from '../Sheet/index.js'
import { Button } from '../Button/index.js'
import { Text } from '../Text/index.js'
import { IconButton } from '../IconButton/index.js'
import { SelectInput } from '../SelectInput/index.js'
import { Schema, SchemaTypeName } from '@based/schema'
import { Sort } from '../../utils/common.js'

type SortInputProps = {
  type: SchemaTypeName
  value?: Sort
  onChange: (value: Sort) => void
  schema?: Schema
}
function SortInput({ type, value, onChange, schema }: SortInputProps) {
  const typeFields = useMemo(() => {
    if (!schema) return

    return schema.types[type].props
  }, [schema, type])

  return (
    <Sheet>
      <Sheet.Trigger>
        {({ open }) => (
          <Button
            loading={!typeFields}
            forceHover={open}
            leadIcon="sort"
            variant="ghost"
            counter={value ? 1 : undefined}
          >
            Sort
          </Button>
        )}
      </Sheet.Trigger>
      <Sheet.Content>
        <div
          style={{
            width: 616,
            display: 'flex',
            flexDirection: 'column',
            gap: 8,
          }}
        >
          <div
            style={{
              display: 'flex',
              padding: '0 8px',
              height: 36,
              alignItems: 'center',
            }}
          >
            <Text variant="subtext-medium" color="neutral60">
              Sort items by...
            </Text>
          </div>
          {value && (
            <SortItemInput
              schema={schema}
              type={type}
              value={value}
              onChange={onChange}
            />
          )}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {!value && (
              <Button
                onClick={() => {
                  onChange({ key: '', direction: '' })
                }}
                variant="ghost"
                leadIcon="add"
              >
                Add sort
              </Button>
            )}
            {value && (
              <Button
                onClick={() => {
                  onChange(undefined)
                }}
                variant="ghost"
                leadIcon="close"
              >
                Clear
              </Button>
            )}
          </div>
        </div>
      </Sheet.Content>
    </Sheet>
  )
}

type SortItemInputProps = {
  type: SchemaTypeName
  value: Sort
  onChange: (value: Sort) => void
  schema?: Schema
}
function SortItemInput({ type, value, onChange, schema }: SortItemInputProps) {
  const fieldOptions = useMemo(() => {
    if (!schema) return

    return Object.keys(schema.types[type].props).map((e) => ({
      value: e,
      label: e,
    }))
  }, [schema, type])
  return (
    <div
      style={{
        width: '100%',
        paddingLeft: 8,
        paddingRight: 8,
        display: 'flex',
        gap: 8,
        alignItems: 'center',
      }}
    >
      <SelectInput
        value={value.key}
        onChange={(key) => {
          onChange({ ...value, key: key as string })
        }}
        options={fieldOptions}
      />
      <SelectInput
        value={value.direction}
        onChange={(direction) => {
          onChange({ ...value, direction: direction as Sort['direction'] })
        }}
        options={[
          { value: 'asc', label: 'Ascending' },
          { value: 'desc', label: 'Descending' },
        ]}
      />
    </div>
  )
}

export { SortInput }
export type { SortInputProps }
