import { useState, useCallback, useRef, useEffect } from "react";
import { Panel, Group as PanelGroup, Separator as PanelResizeHandle } from "react-resizable-panels";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Toaster } from "sonner";
import { AppMenubar } from "@/components/Menubar";
import { FileTree } from "@/components/FileTree";
import { SearchPanel } from "@/components/SearchPanel";
import { EditorTabs } from "@/components/EditorTabs";
import { Editor, type EditorHandle } from "@/components/Editor";
import { StatusBar } from "@/components/StatusBar";
import { CommandPalette } from "@/components/CommandPalette";
import { QuickOpen } from "@/components/QuickOpen";
import { SettingsDialog } from "@/components/SettingsDialog";
import { GoToLineDialog } from "@/components/GoToLineDialog";
import { WelcomeTab } from "@/components/WelcomeTab";
import { Terminal } from "@/components/Terminal";
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
import { useAutoSave } from "@/hooks/useAutoSave";
import { useStore, actions } from "@/lib/store";
import { applyTheme, loadCustomCSS } from "@/lib/themes";

function App() {
  const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
  const [quickOpenOpen, setQuickOpenOpen] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [goToLineOpen, setGoToLineOpen] = useState(false);
  const { sidebarVisible, sidebarView, terminalVisible, splitEditorPath, tabs, activeTabPath, settings } = useStore();
  const editorRef = useRef<EditorHandle>(null);
  const splitEditorRef = useRef<EditorHandle>(null);

  const activeTab = tabs.find((t) => t.path === activeTabPath);

  const openCommandPalette = useCallback(() => setCommandPaletteOpen(true), []);
  const openQuickOpen = useCallback(() => setQuickOpenOpen(true), []);
  const openSettings = useCallback(() => setSettingsOpen(true), []);
  const openGoToLine = useCallback(() => setGoToLineOpen(true), []);

  const handleToggleTerminal = useCallback(() => actions.toggleTerminal(), []);
  const handleSearchInFiles = useCallback(() => actions.setSidebarView("search"), []);
  const handleToggleSplitEditor = useCallback(() => {
    if (splitEditorPath) {
      actions.setSplitEditor(null);
    } else if (activeTabPath) {
      actions.setSplitEditor(activeTabPath);
    }
  }, [splitEditorPath, activeTabPath]);

  const handleGoToLine = useCallback((line: number) => {
    editorRef.current?.goToLine(line);
  }, []);

  useKeyboardShortcuts({
    onOpenCommandPalette: openCommandPalette,
    onOpenQuickOpen: openQuickOpen,
    onToggleTerminal: handleToggleTerminal,
    onSearchInFiles: handleSearchInFiles,
    onGoToLine: openGoToLine,
    onSplitEditor: handleToggleSplitEditor,
  });

  useAutoSave();

  // Apply theme on mount and when theme changes
  useEffect(() => {
    applyTheme(settings.theme);
  }, [settings.theme]);

  // Load custom CSS on mount and when path changes
  useEffect(() => {
    loadCustomCSS(settings.customCssPath);
  }, [settings.customCssPath]);

  const maxLine = activeTab ? activeTab.content.split("\n").length : undefined;

  return (
    <TooltipProvider delayDuration={300}>
      <div className="flex h-screen flex-col overflow-hidden bg-background text-foreground">
        {/* Menubar */}
        <AppMenubar
          onOpenCommandPalette={openCommandPalette}
          onOpenQuickOpen={openQuickOpen}
          onOpenSettings={openSettings}
          onToggleTerminal={handleToggleTerminal}
          onSearchInFiles={handleSearchInFiles}
          onGoToLine={openGoToLine}
          onSplitEditor={handleToggleSplitEditor}
        />

        {/* Main content */}
        <div className="flex-1 overflow-hidden">
          <PanelGroup orientation="horizontal">
            {/* Sidebar */}
            {sidebarVisible && (
              <>
                <Panel
                  defaultSize="20%"
                  minSize="10%"
                  maxSize="40%"
                  className="bg-sidebar-background"
                >
                  {sidebarView === "files" ? <FileTree /> : <SearchPanel />}
                </Panel>
                <PanelResizeHandle className="w-[1px] bg-border hover:bg-primary transition-colors" />
              </>
            )}

            {/* Editor + Terminal vertical split */}
            <Panel minSize="30%">
              <PanelGroup orientation="vertical">
                {/* Editor area */}
                <Panel minSize="20%">
                  <div className="flex h-full flex-col">
                    <EditorTabs />
                    <div className="flex-1 overflow-hidden bg-background">
                      {tabs.length === 0 ? (
                        <WelcomeTab />
                      ) : (
                        <PanelGroup orientation="horizontal">
                          <Panel minSize="30%">
                            <Editor ref={editorRef} />
                          </Panel>
                          {splitEditorPath && (
                            <>
                              <PanelResizeHandle className="w-[1px] bg-border hover:bg-primary transition-colors" />
                              <Panel minSize="20%">
                                <Editor ref={splitEditorRef} tabPath={splitEditorPath} />
                              </Panel>
                            </>
                          )}
                        </PanelGroup>
                      )}
                    </div>
                  </div>
                </Panel>

                {/* Terminal */}
                {terminalVisible && (
                  <>
                    <PanelResizeHandle className="h-[1px] bg-border hover:bg-primary transition-colors" />
                    <Panel defaultSize="30%" minSize="10%" maxSize="70%">
                      <Terminal />
                    </Panel>
                  </>
                )}
              </PanelGroup>
            </Panel>
          </PanelGroup>
        </div>

        {/* Status bar */}
        <StatusBar />
      </div>

      {/* Dialogs */}
      <CommandPalette
        open={commandPaletteOpen}
        onOpenChange={setCommandPaletteOpen}
        onOpenSettings={openSettings}
        onToggleTerminal={handleToggleTerminal}
        onSearchInFiles={handleSearchInFiles}
        onGoToLine={openGoToLine}
        onSplitEditor={handleToggleSplitEditor}
      />
      <QuickOpen open={quickOpenOpen} onOpenChange={setQuickOpenOpen} />
      <SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
      <GoToLineDialog
        open={goToLineOpen}
        onOpenChange={setGoToLineOpen}
        onGoToLine={handleGoToLine}
        maxLine={maxLine}
      />

      <Toaster
        position="bottom-right"
        toastOptions={{
          style: {
            background: "var(--color-card)",
            border: "1px solid var(--color-border)",
            color: "var(--color-foreground)",
          },
        }}
      />
    </TooltipProvider>
  );
}

export default App;
