import { useMemo } from "react";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import { PanelLeftClose, PanelLeftOpen, Play, RotateCw, Square, Terminal } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { EditorPanel } from "@/components/editor/EditorPanel";
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
import { FileExplorerPanel } from "@/components/workspace/FileExplorerPanel";
import { StatusBar } from "@/components/workspace/StatusBar";
import { WorkspaceSelector } from "@/components/workspace/WorkspaceSelector";
import { useWorkspaceUiStore } from "@/lib/store/workspace-ui-store";
import {
  useProcessRestart,
  useProcessStart,
  useProcessStatus,
  useProcessStop,
} from "@/lib/api/process";

interface WorkspaceShellProps {
  workspaceId: string | null;
}

export function WorkspaceShell({ workspaceId }: WorkspaceShellProps) {
  const activeFilePath = useWorkspaceUiStore((s) => s.activeFilePath);
  const sidebarCollapsed = useWorkspaceUiStore((s) => s.sidebarCollapsed);
  const terminalVisible = useWorkspaceUiStore((s) => s.terminalVisible);
  const toggleSidebar = useWorkspaceUiStore((s) => s.toggleSidebar);
  const toggleTerminal = useWorkspaceUiStore((s) => s.toggleTerminal);

  const status = useProcessStatus(workspaceId);
  const start = useProcessStart();
  const stop = useProcessStop();
  const restart = useProcessRestart();

  const isRunning = status.data?.running ?? false;
  const statusUnknown = status.isPending || status.isError;

  const mutationError = useMemo(
    () => start.error ?? stop.error ?? restart.error,
    [start.error, stop.error, restart.error],
  );

  return (
    <div className="flex h-full w-full flex-col bg-background text-foreground">
      {/* Toolbar */}
      <header className="flex h-9 shrink-0 items-center gap-1 border-b border-border bg-sidebar px-3">
        <h1 className="text-sm font-semibold">codespace</h1>
        <Separator orientation="vertical" className="mx-2 h-4" />
        <WorkspaceSelector />
        <Separator orientation="vertical" className="mx-2 h-4" />
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={toggleSidebar}
          >
            {sidebarCollapsed ? (
              <PanelLeftOpen className="size-4" aria-hidden="true" />
            ) : (
              <PanelLeftClose className="size-4" aria-hidden="true" />
            )}
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={toggleTerminal}
          >
            <Terminal className="size-4" aria-hidden="true" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={() => workspaceId && start.mutate(workspaceId)}
            disabled={!workspaceId || statusUnknown || isRunning || start.isPending}
          >
            <Play className="size-4" aria-hidden="true" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={() => workspaceId && stop.mutate(workspaceId)}
            disabled={!workspaceId || statusUnknown || !isRunning || stop.isPending}
          >
            <Square className="size-4" aria-hidden="true" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={() => workspaceId && restart.mutate(workspaceId)}
            disabled={!workspaceId || statusUnknown || !isRunning || restart.isPending}
          >
            <RotateCw
              className={cn("size-4", restart.isPending && "animate-spin")}
              aria-hidden="true"
            />
          </Button>
          {mutationError && (
            <span className="ml-1 text-[11px] text-destructive">
              {mutationError.message}
            </span>
          )}
        </div>
      </header>

      {/* Main layout */}
      {workspaceId ? (
        <div className="flex min-h-0 flex-1">
          <PanelGroup direction="horizontal" className="flex-1">
            {/* Sidebar */}
            {!sidebarCollapsed && (
              <>
                <Panel defaultSize={18} minSize={12} maxSize={30}>
                  <FileExplorerPanel workspaceId={workspaceId} />
                </Panel>
                <PanelResizeHandle className="w-1 bg-border transition-colors hover:bg-accent" />
              </>
            )}

            {/* Main content area */}
            <Panel>
              <PanelGroup direction="vertical">
                {/* Editor */}
                <Panel>
                  <EditorPanel workspaceId={workspaceId} path={activeFilePath || null} />
                </Panel>

                {/* Terminal panel */}
                {terminalVisible && (
                  <>
                    <PanelResizeHandle className="h-1 bg-border transition-colors hover:bg-accent" />
                    <Panel defaultSize={30} minSize={10} maxSize={70}>
                      <TerminalPanel workspaceId={workspaceId} />
                    </Panel>
                  </>
                )}
              </PanelGroup>
            </Panel>
          </PanelGroup>
        </div>
      ) : (
        <main className="flex min-h-0 flex-1 items-center justify-center bg-background text-foreground">
          <div className="text-center text-sm text-muted-foreground">
            <p className="font-medium">No workspace selected</p>
            <p className="mt-1">Select or create a workspace to get started.</p>
            <p className="mt-1 text-xs">Use the workspace selector in the toolbar to choose one.</p>
          </div>
        </main>
      )}

      {/* Status bar */}
      <StatusBar activeFilePath={activeFilePath} workspaceId={workspaceId} />
    </div>
  );
}
