import {PencilIcon, TrashIcon} from '@heroicons/react/solid'
import React, {useEffect, useState} from 'react'

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

const ScenarioTable: React.FC<IScenarioList> = ({ list, indicators = [], setScenarios }) => {
  const [rows, setRows] = useState<ScenarioViewModel[]>([])
  const [showUpdateModal, setShowUpdateModal] = useState(false)
  const [selectedScenario, setSelectedScenario] = useState<ScenarioViewModel | null>(null)
  const { apiUrl } = useApiUrlStore()
  const client = new ScenarioClient({}, apiUrl)

  async function deleteScenario(id: string) {
    const t = new Toast('Deleting scenario')

    await client
      .scenario_DeleteScenario(id)
      .then(() => {
        t.update('success', 'Scenario deleted')
        // Refetch scenarios after deletion
        if (setScenarios) {
          client.scenario_GetScenarios().then((scenarios) => {
            setScenarios(scenarios)
          })
        }
      })
      .catch((err) => {
        t.update('error', err)
      })
  }

  async function updateScenario(form: IScenarioFormInput) {
    const t = new Toast('Updating scenario')
    
    await client
      .scenario_UpdateScenario(form.name, form.loopbackPeriod, form.indicators)
      .then(() => {
        t.update('success', 'Scenario updated')
        // Refetch scenarios after update since the API returns FileResponse
        if (setScenarios) {
          client.scenario_GetScenarios().then((scenarios) => {
            setScenarios(scenarios)
          })
        }
      })
      .catch((err) => {
        t.update('error', err)
      })
  }

  function openUpdateModal(scenario: ScenarioViewModel) {
    setSelectedScenario(scenario)
    setShowUpdateModal(true)
  }

  function closeUpdateModal() {
    setShowUpdateModal(false)
    setSelectedScenario(null)
  }

  const handleUpdateSubmit = async (form: IScenarioFormInput) => {
    await updateScenario(form)
  }

  const columns = React.useMemo(
    () => [
      {
        Header: 'Name',
        accessor: 'name',
        disableFilters: true,
      },
      {
        Cell: ({ cell }: any) => (
          <>
            {cell.row.values.indicators.map((indicator: IndicatorViewModel) => (
              <div
                key={indicator.name}
                className="badge badge-primary badge-outline"
              >
                {indicator.name}
              </div>
            ))}
          </>
        ),
        Header: 'Indicators',
        accessor: 'indicators',
        disableFilters: true,
      },
      {
        Cell: ({ cell }: any) => (
          <div className="flex gap-2">
            <div className="tooltip" data-tip="Update scenario">
              <button
                data-value={cell.row.values.name}
                onClick={() => openUpdateModal(cell.row.original)}
                className="btn btn-ghost btn-sm"
              >
                <PencilIcon className="text-info w-4" />
              </button>
            </div>
            <div className="tooltip" data-tip="Delete scenario">
              <button
                data-value={cell.row.values.name}
                onClick={() => deleteScenario(cell.row.values.name)}
                className="btn btn-ghost btn-sm"
              >
                <TrashIcon className="text-accent w-4" />
              </button>
            </div>
          </div>
        ),
        Header: 'Actions',
        accessor: 'id',
        disableFilters: true,
      },
    ],
    []
  )

  useEffect(() => {
    setRows(list)
  }, [list])

  return (
    <div className="flex flex-wrap">
      <Table columns={columns} data={rows} showPagination={true} />
      
      {/* Update Modal */}
      <ScenarioModal
        showModal={showUpdateModal}
        onClose={closeUpdateModal}
        onSubmit={handleUpdateSubmit}
        indicators={indicators}
        scenario={selectedScenario}
        isUpdate={true}
      />
    </div>
  )
}

export default ScenarioTable
