import { useState } from 'react'
import { Button, Modal } from 'antd'
import { useViewChartQuery } from '@/hooks/useChartQuery'
import Chart from './Chart'

export default function ViewDataButtonModal({ id }: { id: string }) {
  const [open, setOpen] = useState(false)

  return (
    <>
      <Button color="primary" variant="text" onClick={() => setOpen(true)}>
        查看
      </Button>
      <Modal title="查看" width={'80%'} open={open} footer={null} onCancel={() => setOpen(false)} destroyOnClose={true}>
        <ModalContent id={id} />
      </Modal>
    </>
  )
}

// 分离Modal内容到单独组件，只在Modal打开时渲染并执行查询
function ModalContent({ id }: { id: string }) {
  const { data, isLoading } = useViewChartQuery(id)

  if (isLoading) {
    return <div>加载中...</div>
  }

  if (!data) {
    return <div>暂无数据</div>
  }

  const { config } = JSON.parse(data.content)

  return (
    <div>
      <Chart type={data.type} {...config} />
    </div>
  )
}
