import type { FileUpload } from '@/app/components/base/features/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@langgenius/dify-ui/popover'
import { RiUploadCloud2Line } from '@remixicon/react'
import {
  memo,
  useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { FILE_URL_REGEX } from '../constants'
import FileInput from '../file-input'
import { useFile } from '../hooks'
import { useStore } from '../store'

type FileFromLinkOrLocalProps = {
  showFromLink?: boolean
  showFromLocal?: boolean
  trigger: (open: boolean) => React.ReactNode
  fileConfig: FileUpload
}
const FileFromLinkOrLocal = ({
  showFromLink = true,
  showFromLocal = true,
  trigger,
  fileConfig,
}: FileFromLinkOrLocalProps) => {
  const { t } = useTranslation()
  const files = useStore(s => s.files)
  const [open, setOpen] = useState(false)
  const [url, setUrl] = useState('')
  const [showError, setShowError] = useState(false)
  const { handleLoadFileFromLink } = useFile(fileConfig)
  const disabled = !!fileConfig.number_limits && files.length >= fileConfig.number_limits
  const fileLinkPlaceholder = t('fileUploader.pasteFileLinkInputPlaceholder', { ns: 'common' })
  /* v8 ignore next -- fallback for a missing i18n key is not reliably testable under the current global translation mocks in the test DOM runtime. @preserve */
  const fileLinkPlaceholderText = fileLinkPlaceholder || ''

  const handleSaveUrl = () => {
    /* v8 ignore next -- guarded by UI-level disabled state (`disabled={!url || disabled}`), not reachable in the current test click flow. @preserve */
    if (!url)
      return

    if (!FILE_URL_REGEX.test(url)) {
      setShowError(true)
      return
    }
    handleLoadFileFromLink(url)
    setUrl('')
  }

  return (
    <Popover
      open={open}
      onOpenChange={setOpen}
    >
      <PopoverTrigger render={trigger(open) as React.ReactElement} />
      <PopoverContent
        placement="top"
        sideOffset={4}
        popupClassName="border-none bg-transparent shadow-none"
      >
        <div className="w-[280px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-lg">
          {
            showFromLink && (
              <>
                <div className={cn(
                  'flex h-8 items-center rounded-lg border border-components-input-border-active bg-components-input-bg-active p-1 shadow-xs',
                  showError && 'border-components-input-border-destructive',
                )}
                >
                  <input
                    className="mr-0.5 block grow appearance-none bg-transparent px-1 system-sm-regular outline-hidden"
                    placeholder={fileLinkPlaceholderText}
                    value={url}
                    onChange={(e) => {
                      setShowError(false)
                      setUrl(e.target.value.trim())
                    }}
                    disabled={disabled}
                  />
                  <Button
                    className="shrink-0"
                    size="small"
                    variant="primary"
                    disabled={!url || disabled}
                    onClick={handleSaveUrl}
                  >
                    {t('operation.ok', { ns: 'common' })}
                  </Button>
                </div>
                {
                  showError && (
                    <div className="mt-0.5 body-xs-regular text-text-destructive">
                      {t('fileUploader.pasteFileLinkInvalid', { ns: 'common' })}
                    </div>
                  )
                }
              </>
            )
          }
          {
            showFromLink && showFromLocal && (
              <div className="flex h-7 items-center p-2 system-2xs-medium-uppercase text-text-quaternary">
                <div className="mr-2 h-px w-[93px] bg-linear-to-l from-[rgba(16,24,40,0.08)]" />
                OR
                <div className="ml-2 h-px w-[93px] bg-linear-to-r from-[rgba(16,24,40,0.08)]" />
              </div>
            )
          }
          {
            showFromLocal && (
              <Button
                className="relative w-full"
                variant="secondary-accent"
                disabled={disabled}
              >
                <RiUploadCloud2Line className="mr-1 size-4" />
                {t('fileUploader.uploadFromComputer', { ns: 'common' })}
                <FileInput fileConfig={fileConfig} />
              </Button>
            )
          }
        </div>
      </PopoverContent>
    </Popover>
  )
}

export default memo(FileFromLinkOrLocal)
