import { useRef } from 'react';
import { Loader2, Folder, ClipboardPaste, FolderPlus, FolderUp, LayoutGrid, Upload, ClipboardCopy, MessageSquare, Download, Mic } from 'lucide-react';
import { getIcon } from 'material-file-icons';
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu';
import type { UseFileBrowserAppType } from '../useFileBrowserApp';
import { FileGrid } from './FileGrid';

type FileViewContainerProps = {
  fileBrowserManager: UseFileBrowserAppType;
};

export const FileViewContainer = ({ fileBrowserManager }: FileViewContainerProps) => {
  const {
    searchQuery,
    searching,
    searchResults,
    handleSearchResultClick,
    dragging,
    handleDragEnter,
    handleDragLeave,
    handleDragOver,
    handleDrop,
    fileScrollRef,
    handleBackgroundClick,
    loading,
    handlePaste,
    handleCopyCurrentPath,
    handleChatHere,
    handleCreateDir,
    handleCreateDashboardHere,
    setShowVideoDownload,
    setShowDictate,
    handleUpload,
  } = fileBrowserManager;

  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const folderInputRef = useRef<HTMLInputElement | null>(null);

  const handleFileChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
    if (ev.target.files?.length) {
      handleUpload(ev.target.files);
      ev.target.value = '';
    }
  };

  return (
    <div
      className="flex-1 min-h-0 relative"
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {dragging && (
        <div className="absolute inset-0 z-50 flex items-center justify-center bg-duck-teal/10 border-2 border-dashed border-duck-teal rounded-lg m-2 pointer-events-none">
          <div className="flex flex-col items-center gap-2 text-duck-teal">
            <Upload className="h-8 w-8" />
            <span className="text-sm font-medium">Drop files to upload</span>
          </div>
        </div>
      )}
      {searchQuery.trim() ? (
        <div className="h-full overflow-auto p-4">
          {searching ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="h-6 w-6 text-duck-teal animate-spin" />
            </div>
          ) : searchResults && searchResults.length > 0 ? (
            <div className="flex flex-col">
              {searchResults.map((entry) => {
                const isDir = entry.type === 'directory';
                return (
                  <div
                    key={entry.path}
                    className="flex items-center gap-3 px-3 py-2 hover:bg-duck-teal/5 cursor-pointer border-b border-duck-dark/5 last:border-b-0"
                    onClick={() => handleSearchResultClick(entry)}
                  >
                    {isDir ? (
                      <Folder className="h-5 w-5 shrink-0 text-duck-yellow fill-duck-yellow/30" />
                    ) : (
                      <span
                        className="inline-flex h-5 w-5 shrink-0"
                        dangerouslySetInnerHTML={{ __html: getIcon(entry.name).svg }}
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      <span className="text-sm font-medium text-duck-dark block truncate">{entry.name}</span>
                      <span className="text-xs text-duck-dark/40 block truncate">{entry.path}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : searchResults ? (
            <div className="flex items-center justify-center py-20 text-duck-dark/40 text-sm">
              No results found
            </div>
          ) : null}
        </div>
      ) : (
        <ContextMenu>
          <ContextMenuTrigger asChild>
            <div ref={fileScrollRef} className="h-full overflow-auto p-4" onClick={handleBackgroundClick}>
              {loading ? (
                <div className="flex items-center justify-center h-full">
                  <Loader2 className="h-6 w-6 text-duck-teal animate-spin" />
                </div>
              ) : (
                <FileGrid fileBrowserManager={fileBrowserManager} />
              )}
            </div>
          </ContextMenuTrigger>
          <ContextMenuContent className="z-[600]">
            <ContextMenuItem onClick={handleCopyCurrentPath} className="cursor-pointer">
              <ClipboardCopy className="mr-2 h-4 w-4" />
              Copy path
            </ContextMenuItem>
            <ContextMenuItem onClick={handleChatHere} className="cursor-pointer">
              <MessageSquare className="mr-2 h-4 w-4" />
              Chat about this
            </ContextMenuItem>
            <ContextMenuItem onClick={handlePaste} className="cursor-pointer">
              <ClipboardPaste className="mr-2 h-4 w-4" />
              Paste
            </ContextMenuItem>
            <ContextMenuItem
              onClick={() => {
                const name = prompt('Folder name');
                if (name?.trim()) handleCreateDir(name.trim());
              }}
              className="cursor-pointer"
            >
              <FolderPlus className="mr-2 h-4 w-4" />
              New folder
            </ContextMenuItem>
            <ContextMenuItem onClick={() => fileInputRef.current?.click()} className="cursor-pointer">
              <Upload className="mr-2 h-4 w-4" />
              Upload files
            </ContextMenuItem>
            <ContextMenuItem onClick={() => folderInputRef.current?.click()} className="cursor-pointer">
              <FolderUp className="mr-2 h-4 w-4" />
              Upload folder
            </ContextMenuItem>
            <ContextMenuItem onClick={handleCreateDashboardHere} className="cursor-pointer">
              <LayoutGrid className="mr-2 h-4 w-4" />
              Create Dashboard here
            </ContextMenuItem>
            <ContextMenuItem onClick={() => setShowVideoDownload(true)} className="cursor-pointer">
              <Download className="mr-2 h-4 w-4" />
              Download video
            </ContextMenuItem>
            <ContextMenuItem onClick={() => setShowDictate(true)} className="cursor-pointer">
              <Mic className="mr-2 h-4 w-4" />
              Dictate
            </ContextMenuItem>
          </ContextMenuContent>
        </ContextMenu>
      )}
      <input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileChange} />
      <input
        ref={(input) => {
          folderInputRef.current = input;
          if (input) input.setAttribute('webkitdirectory', '');
        }}
        type="file"
        className="hidden"
        onChange={handleFileChange}
      />
    </div>
  );
};
