import { UI } from '@hyext/hy-ui'
import React, { useState, useRef, PropsWithChildren, ReactElement } from 'react'
import './index.hycss'
import '@hyext/tailwindcss/styles.hycss'
import { ViewStyle, ImageStyle, View, Text } from 'react-native'
import Abnor from '../Abnor'

const { ScrollView, Image } = UI

export type Source<T> = {
  key: keyof T // data item key
  title: string // 标题
  render: (v: ToValues<T, keyof T>, record: T, index: number) => ReactElement // 列单元渲染
  className?: string // 列样式
}

type ITableProps<T> = {
  dataSource: Source<T>[]
  data: T[]
  rowStyle?: ViewStyle // 行样式
  style?: ViewStyle // contianer 样式
  empty?: string | ReactElement
}

export function Table<T>(props: ITableProps<T>) {
  const { dataSource, style } = props

  return (
    <View className="flex-1" style={style}>
      <TableTitle list={dataSource}></TableTitle>
      <TableBody {...props}></TableBody>
    </View>
  )
}

function TableTitle<T>(props: { list: Pick<Source<T>, 'title'>[] }) {
  const list = props.list

  return (
    <View className="flex-row items-center TableTitle">
      {list.map((item, i) => {
        return (
          <View className="flex-1 justify-center items-center" key={i}>
            <Text className="bold">{item.title}</Text>
          </View>
        )
      })}
    </View>
  )
}

function TableBody<T>(props: ITableProps<T>) {
  const { dataSource, data, rowStyle, empty } = props

  if (data.length === 0) {
    if (React.isValidElement(empty)) {
      return empty
    } else {
      return (
        <ScrollView className="flex-1">
          {/* @ts-expect-error */}
          <Abnor type="empty" desc={empty || '列表空空如也~'}></Abnor>
        </ScrollView>
      )
    }
  }

  return (
    <ScrollView className="flex-1">
      <View>
        {data.map((item, i) => {
          return (
            <TableRow
              style={rowStyle}
              data={item}
              sources={dataSource}
              key={i}
              index={i}
            ></TableRow>
          )
        })}
      </View>
    </ScrollView>
  )
}

function TableRow<T>(props: {
  data: T
  sources: Source<T>[]
  style?: ViewStyle
  index: number
}) {
  const { data, sources, index, style } = props

  return (
    <View className="flex-row w-full">
      {sources.map((source, i) => {
        const { key, render, className } = source
        const val = data[key]
        return (
          <View
            className={`flex-1 justify-center items-center ${className}`}
            style={style}
            key={i}
          >
            {render(val, data, index)}
          </View>
        )
      })}
    </View>
  )
}
