import {
  randAirportCode,
  randEmail,
  randFullName,
  randImg,
} from '@ngneat/falso'
import { useCallback, useMemo, useState } from 'react'
import { Fields, Select, Sort } from '../../utils/common.js'
import { useToast } from '../Toast/index.js'
import { Table, TableProps } from './index.js'
import { Badge } from '../Badge/index.js'
import { Text } from '../Text/index.js'
import { Media } from '../Media/index.js'

const TEST_DATA = Array.from({ length: 1000 }).map((_, index) => ({
  id: index,
  name: randFullName(),
  email: randEmail(),
  airport: randAirportCode(),
  src: randImg(),
}))

export const Regular = () => {
  const [first, setFirst] = useState(0)
  const [last, setLast] = useState(0)
  const [sort, setSort] = useState<Sort>()
  const [select, setSelect] = useState<Select>()
  const toast = useToast()

  const fields = useMemo(
    () =>
      ({
        id: {
          key: 'id',
          render: (item) => <Badge>{item.id}</Badge>,
        },
        src: {
          key: 'src',
          table: { width: 24, title: '' },
          render: (row) => (
            <div style={{ height: 24, width: 24, display: 'flex' }}>
              <Media data={row} />
            </div>
          ),
        },
        name: {
          key: 'name',
          render: (row) => <Text color="red100">{row.name}</Text>,
        },
        name2: {
          key: 'name',
          render: (row) => <Text color="red100">{row.name}</Text>,
        },
        name3: {
          key: 'name',
          render: (row) => <Text color="red100">{row.name}</Text>,
        },
        email: {
          key: 'email',
          render: (row) => <Text>{row.name}</Text>,
        },
        airport: {
          key: 'airport',
          table: { width: 50 },
          render: (row) => <Badge>{row.airport}</Badge>,
        },
      }) satisfies Fields,
    [],
  )
  const itemActions = useMemo(
    () =>
      [
        {
          label: 'Delete',
          color: 'red',
          icon: 'delete',
          onClick: (item) => {
            console.log('delete', item.id)
          },
        },
      ] satisfies TableProps['itemActions'],
    [],
  )
  const handleScroll = useCallback((first: number, last: number) => {
    setFirst(first)
    setLast(last)
  }, [])
  const onItemClick = useCallback(
    ((item) => {
      toast(`clicked item ${item.id}`)
    }) satisfies TableProps['onItemClick'],
    [],
  )

  return (
    <div style={{ height: '100svh' }}>
      <Table
        fields={fields}
        data={TEST_DATA.slice(first, last)}
        total={TEST_DATA.length}
        sort={sort}
        onSortChange={setSort}
        select={select}
        onSelectChange={setSelect}
        onScroll={handleScroll}
        onItemClick={onItemClick}
        itemActions={itemActions}
        layout="showAllColumns"
      />
    </div>
  )
}
