import { useState, useCallback, useRef } from 'react'
import { FolderButton } from '../folder-button'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
} from '../../basic/dropdown-menu'
import { FolderPermissionDialog } from './folder-permission-dialog'
import { FolderLine, FolderFillLine, TimeLine } from '../../basic/icons-inline'
import type { FolderPermissionConfig, InputPropsWithWebkitDirectory } from './types'

const MOCK_HISTORY_FOLDERS = ['~/Projects/spark-design-app', '~/Documents/workspace', '~/Desktop/demo', '~/code/my-app']

const iconClass = 'mr-2 w-4 h-4 shrink-0'

export interface ChatInputFolderSelectorProps {
  disabled: boolean
  folderButtonLabel: string
  folderPermission?: FolderPermissionConfig
  onFolderButtonClick?: () => void
  onFolderClear?: () => void
  onFolderSelect: (files: FileList) => void
  hasFolderSelected: boolean
  dataStyle?: string
  dataTheme?: string
  folderIcon?: React.ReactNode
  folderOpenIcon?: React.ReactNode
  historyIcon?: React.ReactNode
  subMenuArrowIcon?: React.ReactNode
  folderFillIcon?: React.ReactNode
  closeIcon?: React.ReactNode
}

export function ChatInputFolderSelector({
  disabled,
  folderButtonLabel,
  folderPermission,
  onFolderButtonClick,
  onFolderClear,
  onFolderSelect,
  hasFolderSelected,
  dataStyle,
  dataTheme,
  folderIcon = <FolderLine className={iconClass} />,
  folderOpenIcon = <FolderFillLine className={iconClass} />,
  historyIcon = <TimeLine className={iconClass} />,
  subMenuArrowIcon,
  folderFillIcon,
  closeIcon,
}: ChatInputFolderSelectorProps) {
  const enableFolderPermissionDialog = folderPermission?.enable ?? false
  const folderPermissionProjectName = folderPermission?.projectName ?? '04_代码'
  const [folderPermissionOpen, setFolderPermissionOpen] = useState(false)
  const [folderPermissionAlwaysAllow, setFolderPermissionAlwaysAllow] = useState(false)
  const [folderMenuOpen, setFolderMenuOpen] = useState(false)
  const folderInputRef = useRef<HTMLInputElement>(null)

  const handleFolderButtonClick = onFolderButtonClick ?? (() => {})

  const openFolderPicker = () => {
    folderInputRef.current?.click()
  }

  const handleFolderClear = () => {
    if (folderInputRef.current) folderInputRef.current.value = ''
    onFolderClear?.()
  }

  const requestFolderPermission = useCallback((mode: 'once' | 'always') => {
    if (mode === 'always') setFolderPermissionAlwaysAllow(true)
    setFolderPermissionOpen(false)
    setFolderMenuOpen(true)
  }, [])

  const handleFolderMenuOpenChange = (next: boolean) => {
    if (!enableFolderPermissionDialog) {
      setFolderMenuOpen(next)
      return
    }
    if (!next) {
      setFolderMenuOpen(false)
      return
    }
    if (folderPermissionAlwaysAllow) {
      setFolderMenuOpen(true)
      return
    }
    setFolderPermissionOpen(true)
    setFolderMenuOpen(false)
  }

  const handleFolderInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (files && files.length > 0) onFolderSelect(files)
  }

  if (onFolderButtonClick) {
    return (
      <FolderButton
        label={folderButtonLabel}
        onClick={handleFolderButtonClick}
        disabled={disabled}
        folderIcon={folderIcon}
        folderFillIcon={folderFillIcon}
      />
    )
  }

  return (
    <>
      <DropdownMenu open={folderMenuOpen} onOpenChange={handleFolderMenuOpenChange}>
        <DropdownMenuTrigger asChild>
          <FolderButton
            label={folderButtonLabel}
            disabled={disabled}
            selected={hasFolderSelected}
            onClear={handleFolderClear}
            folderIcon={folderIcon}
            folderFillIcon={folderFillIcon}
            closeIcon={closeIcon}
            className="focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0"
          />
        </DropdownMenuTrigger>
        <DropdownMenuContent
          align="start"
          side="top"
          className="min-w-50"
          dataStyle={dataStyle}
          dataTheme={dataTheme}
        >
          <DropdownMenuItem onClick={openFolderPicker}>
            {folderIcon}
            Add folder
          </DropdownMenuItem>
          {hasFolderSelected && (
            <DropdownMenuItem onClick={openFolderPicker}>
              {folderOpenIcon}
              Replace folder
            </DropdownMenuItem>
          )}
          <DropdownMenuSub>
            <DropdownMenuSubTrigger subTriggerIcon={subMenuArrowIcon}>
              {historyIcon}
              Recent folders
            </DropdownMenuSubTrigger>
            <DropdownMenuSubContent
              collisionPadding={{ bottom: 24, left: 8 }}
              dataStyle={dataStyle}
              dataTheme={dataTheme}
            >
              {MOCK_HISTORY_FOLDERS.map((path) => (
                <DropdownMenuItem key={path} onClick={() => {}}>
                  {path}
                </DropdownMenuItem>
              ))}
            </DropdownMenuSubContent>
          </DropdownMenuSub>
        </DropdownMenuContent>
      </DropdownMenu>
      <input
        ref={folderInputRef}
        type="file"
        {...({ webkitdirectory: '' } as InputPropsWithWebkitDirectory)}
        multiple
        style={{ display: 'none' }}
        onChange={handleFolderInputChange}
      />
      {enableFolderPermissionDialog && (
        <FolderPermissionDialog
          open={folderPermissionOpen}
          onOpenChange={setFolderPermissionOpen}
          projectName={folderPermissionProjectName}
          onAllowOnce={() => requestFolderPermission('once')}
          onAllowAlways={() => requestFolderPermission('always')}
        />
      )}
    </>
  )
}

ChatInputFolderSelector.displayName = 'ChatInputFolderSelector'
