import { Box, Skeleton } from '@tidbcloud/uikit'
import { useEffect, useState } from 'react'

import { getEndpointDraftDiff } from 'dbaas/services/dataservice'
import { EntitySnapshotDiff } from 'dbaas/services/dataservice/interface'

import { useDataApiContext } from '../context'
import { TextDiff } from '../DataAppDetail/Deployment/Diff'

const EndpointDraftDiff = ({ maxHeight }: { maxHeight?: string | number }) => {
  const { orgId, projectId, editApp, editEndpoint, editEndpointRef, paramsListRef, sqlTextRef } = useDataApiContext()
  const [diffDetail, setDiffDetail] = useState<EntitySnapshotDiff | undefined>()
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    fetcher()
  }, [])

  const fetcher = async () => {
    setIsLoading(true)
    try {
      const args = paramsListRef.current.map((param) => {
        const cur = { ...param }
        delete cur.value
        return cur
      })

      const res = await getEndpointDraftDiff(
        orgId,
        projectId,
        `${editApp?.id || editEndpoint?.dataappp_id}`,
        `${editEndpoint?.id}`,
        {
          ...editEndpointRef.current,
          sql_template: sqlTextRef.current,
          args
        },
        {
          diff_type: 'text'
        }
      )
      setDiffDetail(res?.data)
    } catch (_e) {
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      {isLoading ? (
        <>
          <Skeleton height={16} radius="xl" />
          <Skeleton height={16} mt={8} radius="xl" />
          <Skeleton height={16} mt={8} radius="xl" />
        </>
      ) : (
        <>
          {diffDetail?.has_diff && (
            <Box
              sx={(theme) => ({
                backgroundColor: theme.colors.carbon[2],
                padding: 16,
                border: `1px solid ${theme.colors.carbon[5]}`,
                borderRadius: theme.defaultRadius,
                maxHeight: maxHeight || '50vh',
                overflow: 'auto'
              })}
            >
              {diffDetail?.text_diff && <TextDiff value={diffDetail?.text_diff} />}
            </Box>
          )}
        </>
      )}
    </>
  )
}

export default EndpointDraftDiff
