import React, {useEffect, useState} from 'react'
import 'react-toastify/dist/ReactToastify.css'

import useApiUrlStore from '../../app/store/apiStore'
import {Toast} from '../../components/mollecules'
import {ScenarioModal} from '../../components/organism'
import type {IndicatorViewModel, ScenarioViewModel} from '../../generated/ManagingApi'
import {ScenarioClient} from '../../generated/ManagingApi'
import type {IScenarioFormInput} from '../../global/type'

import ScenarioTable from './scenarioTable'

const ScenarioList: React.FC = () => {
  const [indicators, setIndicators] = useState<IndicatorViewModel[]>([])
  const [scenarios, setScenarios] = useState<ScenarioViewModel[]>([])
  const [showModal, setShowModal] = useState(false)
  const { apiUrl } = useApiUrlStore()
  const client = new ScenarioClient({}, apiUrl)

  async function createScenario(form: IScenarioFormInput) {
    const t = new Toast('Creating scenario')
    await client
      .scenario_CreateScenario(form.name, form.loopbackPeriod, form.indicators)
      .then((data: ScenarioViewModel) => {
        t.update('success', 'Scenario created')
        setScenarios((arr) => [...arr, data])
      })
      .catch((err) => {
        t.update('error', err)
      })
  }

  const handleSubmit = async (form: IScenarioFormInput) => {
    await createScenario(form)
  }

  useEffect(() => {
    client.scenario_GetScenarios().then((data) => {
      setScenarios(data)
    })
    client.scenario_GetIndicators().then((data) => {
      setIndicators(data)
    })
  }, [])

  function openModal() {
    setShowModal(true)
  }

  function closeModal() {
    setShowModal(false)
  }

  return (
    <div className="container mx-auto">
      <button className="btn" onClick={openModal}>
        Create new scenario
      </button>
      <ScenarioTable list={scenarios} indicators={indicators} setScenarios={setScenarios} />
      <ScenarioModal
        showModal={showModal}
        onClose={closeModal}
        onSubmit={handleSubmit}
        indicators={indicators}
        isUpdate={false}
      />
    </div>
  )
}

export default ScenarioList
