'use client'

import { Button } from '@langgenius/dify-ui/button'
import { Input } from '@langgenius/dify-ui/input'
import { RiAddLine } from '@remixicon/react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useModalContext } from '@/context/modal-context'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/client'
import ExternalApiSelect from './ExternalApiSelect'

type ExternalApiSelectionProps = {
  external_knowledge_api_id: string
  external_knowledge_id: string
  onChange: (data: { external_knowledge_api_id?: string; external_knowledge_id?: string }) => void
}

const ExternalApiSelection: React.FC<ExternalApiSelectionProps> = ({
  external_knowledge_api_id,
  external_knowledge_id,
  onChange,
}) => {
  const { t } = useTranslation()
  const router = useRouter()
  const queryClient = useQueryClient()
  const externalKnowledgeApiQueryOptions =
    consoleQuery.datasets.externalKnowledgeApi.get.queryOptions({ input: {} })
  const { data } = useQuery(externalKnowledgeApiQueryOptions)
  const externalKnowledgeApiList = data?.data ?? []
  const externalKnowledgeIdInputId = useId()
  const [selectedApiId, setSelectedApiId] = useState(external_knowledge_api_id)
  const { setShowExternalKnowledgeAPIModal } = useModalContext()

  const apiItems = externalKnowledgeApiList.map((api) => ({
    value: api.id,
    name: api.name,
    url: api.settings && typeof api.settings.endpoint === 'string' ? api.settings.endpoint : '',
  }))

  useEffect(() => {
    if (apiItems.length > 0) {
      const newSelectedId = external_knowledge_api_id || apiItems[0]!.value
      setSelectedApiId(newSelectedId)
      if (newSelectedId !== external_knowledge_api_id)
        onChange({ external_knowledge_api_id: newSelectedId, external_knowledge_id })
    }
  }, [apiItems, external_knowledge_api_id, external_knowledge_id, onChange])

  const handleAddNewAPI = () => {
    setShowExternalKnowledgeAPIModal({
      payload: { name: '', settings: { endpoint: '', api_key: '' } },
      onSaveCallback: async () => {
        await queryClient.invalidateQueries({
          queryKey: externalKnowledgeApiQueryOptions.queryKey,
        })
        router.refresh()
      },
      isEditMode: false,
    })
  }

  useEffect(() => {
    if (!external_knowledge_api_id && apiItems.length > 0)
      onChange({ external_knowledge_api_id: apiItems[0]!.value, external_knowledge_id })
  }, [])

  return (
    <form className="flex flex-col gap-4 self-stretch">
      <div className="flex flex-col gap-1 self-stretch">
        <div className="flex flex-col self-stretch">
          <label className="system-sm-semibold text-text-secondary">
            {t(($) => $.externalAPIPanelTitle, { ns: 'dataset' })}
          </label>
        </div>
        {apiItems.length > 0 ? (
          <ExternalApiSelect
            items={apiItems}
            value={selectedApiId}
            onSelect={(e) => {
              setSelectedApiId(e.value)
              onChange({ external_knowledge_api_id: e.value, external_knowledge_id })
            }}
          />
        ) : (
          <Button variant="tertiary" onClick={handleAddNewAPI} className="justify-start">
            <RiAddLine className="size-4 text-text-tertiary" />
            <span className="system-sm-regular text-text-tertiary">
              {t(($) => $.noExternalKnowledge, { ns: 'dataset' })}
            </span>
          </Button>
        )}
      </div>
      <div className="flex flex-col gap-1 self-stretch">
        <div className="flex flex-col self-stretch">
          <label
            htmlFor={externalKnowledgeIdInputId}
            className="system-sm-semibold text-text-secondary"
          >
            {t(($) => $.externalKnowledgeId, { ns: 'dataset' })}
          </label>
        </div>
        <Input
          id={externalKnowledgeIdInputId}
          value={external_knowledge_id}
          onValueChange={(value) =>
            onChange({ external_knowledge_id: value, external_knowledge_api_id })
          }
          placeholder={t(($) => $.externalKnowledgeIdPlaceholder, { ns: 'dataset' }) ?? ''}
        />
      </div>
    </form>
  )
}

export default ExternalApiSelection
