import React, {useState} from 'react'
import styled from 'styled-components'
import {useNavigate, useParams} from 'react-router'
import {useMount} from 'ahooks'
import axios from 'axios'
import {commonInfo} from '../../../../util/amis.tsx'
import FlowEditor, {type GraphData} from '../../../../components/flow/FlowEditor.tsx'

const FlowTaskTemplateFlowEditDiv = styled.div`
`

const FlowTaskTemplateFlowEdit: React.FC = () => {
  const navigate = useNavigate()
  const {template_id} = useParams()
  const [graphData, setGraphData] = useState<GraphData>({nodes: [], edges: [], data: {}})

  useMount(async () => {
    let {data} = await axios.get(
      `${commonInfo.baseAiUrl}/flow_task/template/detail/${template_id}`,
      {
        headers: commonInfo.authorizationHeaders
      }
    )
    setGraphData(data?.data?.flowGraph)
  })

  return (
    <FlowTaskTemplateFlowEditDiv className="h-full w-full">
      <FlowEditor
        graphData={graphData}
        onGraphDataChange={async data => {
          await axios.post(
            `${commonInfo.baseAiUrl}/flow_task/template/update_flow_graph`,
            {
              id: template_id,
              graph: data
            },
            {
              headers: commonInfo.authorizationHeaders
            }
          )
          navigate(-1)
        }}
      />
    </FlowTaskTemplateFlowEditDiv>
  )
}

export default FlowTaskTemplateFlowEdit