import moment from 'moment'
import { ref } from 'vue'
import api from '../../../api'
import { useArkUi } from '../../../composables/use-ark-ui'
import type { DataProviderOptionsInterface } from '../../../types/data-provider-interface'
import DefaultButton from '../../buttons/DefaultButton.vue'
import { type ColumnInterface } from '../DefaultTableInterfaces'
import DefaultTable from './DefaultTable.vue'

useArkUi({
  api,
  responseTotalKey: 'count',
  paginationType: 'limit',
  responseItemsKey: 'results',
})

export default {
  title: 'The Design system/Tables/Default table',
  component: DefaultTable,
  tags: ['autodocs'],
  args: {
    title: 'Таблица',
    cacheKey: 'tableSettings',
    showCount: true,
    clearCheckedOnParamsChange: true,
    isFilterBlockNoData: false,
    isExpandRowButton: true,
    enableSorting: true,
    stickyItems: [
      {
        id: 10,
        name: 'Sticky item',
        brand: {
          id: 40,
          name: 'Cadillac',
        },
        article: {
          id: 33,
          name: 'Munchkin',
        },
        city: 'Appleton',
        address: '1857 Adelle Hills',
        color: 'tan',
        region: {
          id: 19,
          name: 'Moldova',
        },
      },
    ],
    totalItems: [
      {
        id: null,
        name: null,
        brand: {
          id: 40,
          name: '1 000',
        },
        article: {
          id: 33,
          name: '3 500',
        },
        city: null,
        address: '9 857',
        color: null,
        region: {
          id: 19,
          name: null,
        },
      },
    ],
    contextActions: [
      { name: 'Test', callback: (item: any) => { console.log('Test context', item) } },
      { name: 'Быстрый просмотр', callback: (item: any) => { console.log('Test context 2', item) } },
      { name: 'Открыть в новом окне', callback: (item: any) => { console.log('Test context 3', item) } },
    ],

    noDataText: '',
    noDataButtonLabel: 'Добавить',
    noDataButtonClick: () => { alert('Кнопка сработала!') },
  },
  argTypes: {
    canCheck: {
      description: 'Вариант отображения чекбоксов',
      control: { type: 'radio' },
      options: ['none', 'one', 'many'],
      defaultValue: 'none',
    },
  },
}

const columns: ColumnInterface[] = [
  {
    name: 'ID',
    visibleByDefault: true,
    sort: 'id',
    field: (item: any) => item.id,
    header: {
      type: 'text',
    },
  },
  {
    name: 'Название + horizontalEyesight',
    visibleByDefault: true,
    sort: 'name',
    field: (item: any) => item.name,
    header: {
      type: 'multipleRelationSelect',
      endpoint: '/product',
      selectedParam: 'name',
    },
    horizontalEyesight: true,
    width: 400,
  },
  {
    name: 'Код (дубль названия)',
    visibleByDefault: true,
    sort: 'name',
    field: (item: any) => item.name,
    header: {
      type: 'multipleRelationSelect',
      endpoint: '/product',
      selectedParam: 'name',
    },
    width: 400,
  },
  {
    name: 'Количество',
    visibleByDefault: true,
    field: (item: any) => item.name,
    header: {
      type: 'numberSearch',
      searchParam: 'count',
    },
    width: 400,
  },
  {
    name: 'Бренд + horizontalEyesight',
    sort: 'brand',
    visibleByDefault: true,
    field: (item: any) => item.brand.name,
    header: {
      type: 'text',
    },
    horizontalEyesight: true,
  },
  {
    name: 'Регион (integer search)',
    sort: 'region',
    visibleByDefault: true,
    field: (item: any) => item.region.name,
    header: {
      type: 'rangeNumber',
      numberType: 'Integer',
      serializationType: 'arkspace',
      arkspaceSerializationTypeParam: 'string',
      // endpoint: '/region'
      // options: [
      //   { id: '1', name: 'Вариант 1' },
      //   { id: '2', name: 'Вариант 2' },
      //   { id: '3', name: 'Вариант 3' },
      //   { id: '4', name: 'Вариант 4' },
      //   { id: '5', name: 'Вариант 5' }
      // ]
    },
  },
  {
    name: 'Регион (float search)',
    sort: 'region',
    visibleByDefault: true,
    field: (item: any) => item.region.name,
    header: {
      type: 'rangeNumber',
      numberType: 'Float',
      serializationType: 'arkspace',
      arkspaceSerializationTypeParam: 'string',
      // endpoint: '/region'
      // options: [
      //   { id: '1', name: 'Вариант 1' },
      //   { id: '2', name: 'Вариант 2' },
      //   { id: '3', name: 'Вариант 3' },
      //   { id: '4', name: 'Вариант 4' },
      //   { id: '5', name: 'Вариант 5' }
      // ]
    },
  },
  {
    name: 'Артикул',
    visibleByDefault: true,
    sort: 'article',
    field: (item: any) => item.article.name,
    header: {
      type: 'text',
    },
  },
  {
    name: 'Город',
    visibleByDefault: false,
    field: (item: any) => item.city,
    header: {
      type: 'text',
    },
  },
  {
    name: 'Адрес салона',
    visibleByDefault: false,
    field: (item: any) => item.address,
    header: {
      type: 'text',
    },
  },
  {
    name: 'Цвет',
    visibleByDefault: false,
    field: (item: any) => item.color,
    header: {
      type: 'text',
    },
  },
  {
    name: 'Мульти параметры',
    visibleByDefault: true,
    field: (item: any) => item.region.name,
    header: {
      type: 'multipleParamsRelationSelect',
      endpoint: '/product',
      titleKey: 'name',
      itemConverter: (v) => ({
        id: v.name + v.region.name, name: v.name, param1: v.region.name, param2: v.brand.name,
      }),
      paramsMap: {
        firstParam: 'param1',
        secondParam: 'param2',
      },
    },
  },
  {
    name: 'Дата',
    field: (item: any) => item.name,
    header: {
      type: 'periodCalendar',
      startDateParam: 'startDateParam',
      endDateParam: 'endDateParam',
      isSetOnlyFullDate: false,
      serializationType: 'default',
      // arkspaceSerializationTypeParam: 'test',
      defaultValue: {
        startDate: moment(),
      },
    },
    // header: {
    //   type: 'calendar',
    //   dateParam: 'startDateParam',
    //   defaultValue: moment(),
    // },
  },
]

const dragAndDropSettings = {
  getSort: (item: any) => item.id,
  setSort: (item: any, n: number) => { item.sort = n },
  onSort: (items: any) => {
    // do nothing
  },
}

/* class Strategy {
  serialize(params: { [code: string]: number|string|string[] }) {
    console.log(this)

    const result = Object.entries(params).reduce((result, [key, value]) => {
      if (Array.isArray(value)) {
        result += value.map((v) => `${key}[]=${encodeURIComponent(String(v))}&`).join('')
      } else {
        result += `${key}[]=${encodeURIComponent(String(value))}&`
      }

      return result
    }, '?')

    console.log('RESULT', result)

    if (Object.keys(params).length > 0) return result.slice(0, result.length - 1)

    return result
  }
} */

const Template = (args: any) => ({
  props: Object.keys(args),
  render() {
    const table = ref()
    const table2 = ref()
    const highlightedElements = ref<Record<string | number, string>>({})

    const setColor = (items: Array<any>, color: string) => {
      items.forEach((i) => {
        highlightedElements.value[i.id] = color
      })
      table.value.clearChecked()
    }

    return (
      <div style="display: flex; flex-direction: column; gap: 30px; max-width: 1200px;">
        <div>
          <DefaultTable
            {...args}
            ref={table}
            endpoint={'/product'}
            columns={columns}
            highlightedElements={highlightedElements.value}
            dragAndDropSorting={dragAndDropSettings}
            canCheck='many'
            canCheckExactItem={(item: any) => (item?.id && item.id > 5)}
            defaultCheckedItems={[{ id: 3 }]}
            smartFilter={true}
            actions={[
              { icon: 'attach', callback: (items: any[]) => { console.log(items) } },
              { icon: 'detach', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'search', callback: (items: any[]) => { console.log(items) }},
              // { icon: 'arrow-down', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-up', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-right', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-up-down', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'calendar', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-2-left', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-2-right', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-down', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-left', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-right', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'chevron-up', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'double-arrow-down', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'double-arrow-up', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'download', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'upload', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'edit', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'filter', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'menu', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'image', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'minus', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'plus', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'production-unit', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'refresh', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'settings', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'trash', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'unit', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'x-cross', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'check', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'check-off', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'copy', callback: (items: any[]) => { setColor(items, '#F6F6FA') } },
              // { icon: 'warning', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'destructive', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'success', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'document', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'loader', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'loader-quarter', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'icon-flow-arrow', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-bend-left', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-bend-right', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-clockwise', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'arrow-counter-clockwise', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'eye-open', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'eye-hide', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'info', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'dots-six-vertical', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'bucket', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'login-ad', callback: (items: any[]) => { console.log(items) } },
              // { icon: 'password-off', callback: (items: any[]) => { console.log(items) } }
            ]}
          />
        </div>
        <div>
          <p class="ark-ui-select-title" style="margin-left: 16px;">Таблица без результатов</p>
          <DefaultTable
            {...args}
            ref={table2}
            endpoint={'nodata'}
            columns={columns}
            buttons={() => (
              <>
                {!table2.value?.isNodataStubVisible && <DefaultButton label={'Кнопка'}/>}
              </>
            )}
          />
        </div>
      </div>
    )
  },
})

export const Primary = Template.bind({})

const dynamicColumns: ColumnInterface[] = [
  {
    name: 'ID',
    visibleByDefault: true,
    sort: 'id',
    field: (item: any) => item.id,
    header: {
      type: 'TextSearch',
      searchParam: 'id',
    },
  },
]

const calculateDynamicColumns = (options: {
  allItems: any[]
  columns: ColumnInterface[]
}) => {
  const maxPeriods = options.allItems.reduce((acc, item) => (item.periods.length > acc ? item.periods.length : acc), 0)

  const result = [...options.columns]

  for (let i = 0; i < maxPeriods; i++) {
    result.push({
      name: `Период ${i}`,
      visibleByDefault: true,
      sort: 'id',
      field: (item: any) => item.periods[i] || '-',
      header: {
        type: 'TextSearch',
        searchParam: `period-${i}`,
      },
    })
  }

  return { columns: result }
}

const DynamicColumnTemplate = (args: any) => ({
  props: Object.keys(args),
  render() {
    return (
      <div style="display: flex; flex-direction: column; gap: 30px;">
        <DefaultTable
          cacheKey='defaultTableWithDynamicColumns'
          endpoint={'/dynamicColumns'}
          columns={dynamicColumns}
          onItemsLoaded={[calculateDynamicColumns]}
          sortFieldKey='sortField'
        />
      </div>
    )
  },
})

export const DynamicColumns = DynamicColumnTemplate.bind({})

function generateDPG(name: string) {
  return async (options: DataProviderOptionsInterface) => {
    const items = [...Array(options.params.limit || 20).keys()].map((i) => i + (options.params.offset || 0)).map((i) => ({ id: `id-${i}`, name: `${name}-item ${i}` }))

    return {
      count: Infinity,
      results: items,
      per_page: options.params.limit || 20,
    }
  }
}

const DataProviderTemplate = (args: any) => ({
  props: Object.keys(args),
  render() {
    return (
      <div style="display: flex; flex-direction: column; gap: 30px;">
        <DefaultTable
          sortFieldKey=''
          dataProvider={{
            get: generateDPG('field'),
          }}
          columns={[
            {
              name: 'Header with DataProvider',
              header: {
                type: 'relationSelect',
                dataProvider: {
                  get: generateDPG('header'),
                },
              },
              field: (item) => <p>{item.name}</p>,
            },
          ]}
        />
      </div>
    )
  },
})

export const DataProvider = DataProviderTemplate.bind({})
