import { Row, Empty, Button, List, Layout } from 'antd'
import React, { useState, useEffect } from 'react'
import { useDispatch, useSelector } from '../../store'
import { scenesSelector, fetchScenes } from '../../store/scene'
import { AddScene } from './add-scene'
import { SignScene, useSceneLinks } from './sign-scene'
import style from './style.module.css'


const { Header, Footer, Sider, Content } = Layout;


export const SceneList = () => {
  const [adding, setAdding] = useState(false)
  const scenes = useSelector(scenesSelector)
  const [link, setLink] = useState('')
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(fetchScenes())
  }, [dispatch])
  const links = scenes.map(useSceneLinks)

  useEffect(() => {
    if (!link && links.length) {
      setLink(links[0].gotoScene)
    }
  }, [link, links])
  
  // const renderScenes = scenes.map(scene => <SignScene {...scene} key={scene.id} />)
  let renderLayer
  
  if (scenes.length) {
    renderLayer = (
      <Layout>
        <Sider>
        <List
          className={style.sceneList}
          loading={false}
          itemLayout="horizontal"
          dataSource={scenes}
          renderItem={scene => <SignScene {...scene} key={scene.id} goto={str => setLink(str)} />} />
        </Sider>
        <Content>
          {link && <iframe src={link} className={style.link}></iframe>}
        </Content>
      </Layout>
    )
  } else {
    renderLayer = <Empty description="暂无数据" image={Empty.PRESENTED_IMAGE_SIMPLE}>
      { <Button type="primary" onClick={() => setAdding(true)}>立即创建</Button> } 
    </Empty>
  }
  const renderHeader = !scenes.length
    ? null
    : <div className={style.header}>
        <Button type="primary" onClick={() => setAdding(true)}>创建场景</Button>
      </div>


  return (
    <div className={style.sceneLayer}>
      { renderHeader }

      <div className="site-card-wrapper">
        { adding && <AddScene onClose={() => setAdding(false)} /> }
        { renderLayer }
      </div>
    </div>
  )
}