import { useState } from 'react'

import styled from 'styled-components'

import Header from './Header'
import Footer from './Footer'
import Policy from './Policy'
import Reward from './Reward'
import Noffy from './Noffy'
import Circle from './Circle'

import global from '../database/global.json'

const Container = styled.div`
  position: relative;
  flex: 1;
  min-height: 100vh;
  padding-top: 45px;
  ${props => props.$background}
`

const Popup = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 50px;
  transform: translate(-50%, -50%);
  z-index: 9;
  background: #f5f5f5;
`

const Button = styled.button`
  padding: 6px 12px;
  background: red;
  color: #fff;
  margin: 10px;
`

const Navbar = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 45px;
  background: #333;
  z-index: 9;
`

function Template({ setTarget, props }) {
  const [template, setTemplate] = useState("");

  const id = props.main.id;
  const className = props.main.className;
  const background = `
    background: ${props.main.styles.background};
    background-repeat: ${props.main.styles.backgroundRepeat};
    background-size: ${props.main.styles.backgroundSize};
  `

  const clickHandle = (evt) => {
    const target = evt.target;
    const isItem = target.classList.contains("ld-item");

    if (isItem) {
      setTarget(target.id);
    }
  }

  return (
    <>
      {template ?
        <Container id={id} className={'ld-item ' + className} $background={background} onClick={clickHandle}>
          <Navbar>
            <Button onClick={() => setTemplate("")}>Chọn Template</Button>
          </Navbar>

          {
            global[template].order.map((type, index) => {
              switch (type) {
                case 'header':
                  return <Header props={props} key={index} />
                case 'circle':
                  return <Circle props={props} key={index} />
                case 'noffy':
                  return <Noffy props={props} key={index} />
                case 'reward':
                  return <Reward props={props} key={index} />
                case 'policy':
                  return <Policy props={props} key={index} />
                case 'footer':
                  return <Footer props={props} key={index} />
                default:
                  return;
              }
            })
          }
        </Container>

        :
        <Container>
          <Popup>
            Chọn Template:

            {
              Object.keys(global).map((id, index) =>
                <Button key={index} onClick={() => setTemplate(id)}>{global[id].name}</Button>
              )
            }
          </Popup>
        </Container>
      }
    </>
  )
}

export default Template