'use client'
import type { FC } from 'react'
import {
  RiAddLine,
  RiArrowDownSLine,
} from '@remixicon/react'
import { useClickAway } from 'ahooks'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
import { Button } from '@/app/components/base/ui/button'
import { toast } from '@/app/components/base/ui/toast'
import { importSchemaFromURL } from '@/service/tools'
import examples from './examples'

type Props = {
  onChange: (value: string) => void
}

const GetSchema: FC<Props> = ({
  onChange,
}) => {
  const { t } = useTranslation()
  const [showImportFromUrl, setShowImportFromUrl] = useState(false)
  const [importUrl, setImportUrl] = useState('')
  const [isParsing, setIsParsing] = useState(false)
  const handleImportFromUrl = async () => {
    if (!importUrl.startsWith('http://') && !importUrl.startsWith('https://')) {
      toast.error(t('createTool.urlError', { ns: 'tools' }))
      return
    }
    setIsParsing(true)
    try {
      const { schema } = await importSchemaFromURL(importUrl) as any
      setImportUrl('')
      onChange(schema)
    }
    finally {
      setIsParsing(false)
      setShowImportFromUrl(false)
    }
  }

  const importURLRef = React.useRef(null)
  useClickAway(() => {
    setShowImportFromUrl(false)
  }, importURLRef)

  const [showExamples, setShowExamples] = useState(false)
  const showExamplesRef = React.useRef(null)
  useClickAway(() => {
    setShowExamples(false)
  }, showExamplesRef)

  return (
    <div className="relative flex w-[224px] justify-end space-x-1">
      <div ref={importURLRef}>
        <Button
          size="small"
          className="space-x-1"
          onClick={() => { setShowImportFromUrl(!showImportFromUrl) }}
        >
          <RiAddLine className="h-3 w-3" />
          <div className="system-xs-medium text-text-secondary">{t('createTool.importFromUrl', { ns: 'tools' })}</div>
        </Button>
        {showImportFromUrl && (
          <div className="absolute top-[26px] left-[-35px] rounded-lg border border-components-panel-border bg-components-panel-bg p-2 shadow-lg">
            <div className="relative">
              <Input
                type="text"
                className="w-[244px]"
                placeholder={t('createTool.importFromUrlPlaceHolder', { ns: 'tools' })!}
                value={importUrl}
                onChange={e => setImportUrl(e.target.value)}
              />
              <Button
                className="absolute top-1 right-1"
                size="small"
                variant="primary"
                disabled={!importUrl}
                onClick={handleImportFromUrl}
                loading={isParsing}
              >
                {isParsing ? '' : t('operation.ok', { ns: 'common' })}
              </Button>
            </div>
          </div>
        )}
      </div>
      <div className="relative -mt-0.5" ref={showExamplesRef}>
        <Button
          size="small"
          className="space-x-1"
          onClick={() => { setShowExamples(!showExamples) }}
        >
          <div className="system-xs-medium text-text-secondary">{t('createTool.examples', { ns: 'tools' })}</div>
          <RiArrowDownSLine className="h-3 w-3" />
        </Button>
        {showExamples && (
          <div className="absolute top-7 right-0 rounded-lg bg-components-panel-bg p-1 shadow-sm">
            {examples.map(item => (
              <div
                key={item.key}
                onClick={() => {
                  onChange(item.content)
                  setShowExamples(false)
                }}
                className="cursor-pointer rounded-lg px-3 py-1.5 system-sm-regular leading-5 whitespace-nowrap text-text-secondary hover:bg-components-panel-on-panel-item-bg-hover"
              >
                {t(`createTool.exampleOptions.${item.key}`, { ns: 'tools' })}
              </div>
            ))}
          </div>
        )}

      </div>
    </div>
  )
}
export default React.memo(GetSchema)
