import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router';
import { useFilesAPI, type DirEntry } from '../../../hooks/useFilesAPI';
import { useRecentFiles } from '../useRecentFiles';
import { usePinnedFiles } from '../usePinnedFiles';

export type Tab = 'browse' | 'recent' | 'pinned';

export const useFileBrowserWidget = () => {
  const navigate = useNavigate();
  const { listDir, search } = useFilesAPI();
  const { recents, addRecent } = useRecentFiles();
  const { pinned, togglePin, isPinned } = usePinnedFiles();

  const [tab, setTab] = useState<Tab>('browse');
  const [browsePath, setBrowsePath] = useState('/');
  const [entries, setEntries] = useState<DirEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<DirEntry[]>([]);
  const [searching, setSearching] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);

  useEffect(() => {
    setLoading(true);
    listDir(browsePath)
      .then((res) => setEntries(res.entries))
      .catch(() => setEntries([]))
      .finally(() => setLoading(false));
  }, [browsePath]);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    const q = searchQuery.trim();
    if (!q) {
      setSearchResults([]);
      return;
    }
    debounceRef.current = setTimeout(() => {
      setSearching(true);
      search(q)
        .then((res) => setSearchResults(res.results))
        .catch(() => setSearchResults([]))
        .finally(() => setSearching(false));
    }, 300);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [searchQuery]);

  const openFile = (path: string, name: string) => {
    addRecent(path, name);
    navigate(`/files?view=${encodeURIComponent(path)}`);
  };

  const isSearching = searchQuery.trim().length > 0;

  const sorted = [...entries].sort((a, b) => {
    if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
    return a.name.localeCompare(b.name);
  });

  return {
    tab,
    setTab,
    browsePath,
    setBrowsePath,
    entries: sorted,
    loading,
    searchQuery,
    setSearchQuery,
    searchResults,
    searching,
    isSearching,
    openFile,
    recents,
    pinned,
    togglePin,
    isPinned,
  };
};

export type UseFileBrowserWidgetType = ReturnType<typeof useFileBrowserWidget>;
