import { Button, Modal } from 'antd'
import AppList, { AppListProps } from '@/components/AppList'
import { getChartComponentList } from '@/api/data'
import { CHART_TYPE } from '@/utils/constants'
import { useState, useEffect } from 'react'
import ViewChartButtonModal from './ViewChartButtonModal'

interface SelectChartProps {
  type?: string
  value?: any[]
  onChange?: (value: any[]) => void
}

export default function SelectChart({ type, value = [], onChange }: SelectChartProps) {
  const [open, setOpen] = useState(false)
  const [selectedRows, setSelectedRows] = useState<any[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [dataSource, setDataSource] = useState<any[]>(value)

  useEffect(() => {
    setDataSource(value)
  }, [value])

  const listOptions: AppListProps = {
    queryKey: ['chartComponentList', { type }],
    fetchApi: async (params) => {
      const { data } = await getChartComponentList({ ...params, type })
      return { ...data }
    },
    columns: [
      {
        title: '序号',
        key: 'index',
        render(_value, _record, index) {
          return index + 1
        },
        width: 62,
        align: 'center',
      },
      {
        title: '组件类型',
        dataIndex: 'type',
        align: 'center',
        render(value: keyof typeof CHART_TYPE) {
          return CHART_TYPE[value] || value
        },
      },
      { title: '组件名称', dataIndex: 'name', align: 'center' },
      { title: '创建人', dataIndex: 'created_operator_name', align: 'center' },
      { title: '创建时间', dataIndex: 'created_time', align: 'center' },
      { title: '更新时间', dataIndex: 'updated_time', align: 'center' },
    ],
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys,
      onChange: (keys: React.Key[], rows: any[]) => {
        setSelectedRowKeys(keys)
        setSelectedRows(rows)
      },
      getCheckboxProps: (record: any) => ({
        disabled: dataSource.some((item) => item.id === record.id),
      }),
    },
  }

  const removeDuplicates = (originalArray: any[], newArray: any[]) => {
    const uniqueArray = [...originalArray]
    newArray.forEach((newItem) => {
      const isDuplicate = uniqueArray.some((item) => item.id === newItem.id)
      if (!isDuplicate) {
        uniqueArray.push(newItem)
      }
    })
    return uniqueArray
  }

  const handleRemove = (record: any) => {
    const newDataSource = dataSource.filter((item) => item.id !== record.id)
    setDataSource(newDataSource)
    onChange?.(newDataSource)
  }

  const handleOk = () => {
    const newDataSource = removeDuplicates(dataSource, selectedRows)
    setDataSource(newDataSource)
    onChange?.(newDataSource)
    setSelectedRows([])
    setSelectedRowKeys([])
    setOpen(false)
  }

  const selectListOptions: AppListProps = {
    dataSource,
    columns: [
      {
        title: '序号',
        key: 'index',
        render(_value, _record, index) {
          return index + 1
        },
        width: 62,
        align: 'center',
      },
      {
        title: '组件类型',
        dataIndex: 'type',
        align: 'center',
        render(value: keyof typeof CHART_TYPE) {
          return CHART_TYPE[value] || value
        },
      },
      { title: '组件名称', dataIndex: 'name', align: 'center' },
      {
        title: '操作',
        key: 'x',
        width: 220,
        align: 'center',
        render(_value, record) {
          return (
            <>
              <ViewChartButtonModal id={record.id}></ViewChartButtonModal>
              <Button color="danger" variant="text" onClick={() => handleRemove(record)}>
                删除
              </Button>
            </>
          )
        },
      },
    ],
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)} style={{ marginBottom: 20 }}>
        添加可视化组件
      </Button>
      <AppList {...selectListOptions} style={{ marginBottom: 20 }} />

      <Modal title="添加可视化组件" width="1000px" open={open} onCancel={() => setOpen(false)} onOk={handleOk}>
        <AppList {...listOptions} />
      </Modal>
    </>
  )
}
