"use client";

import { useState, useEffect, useCallback, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { ArrowLeft, Power, PowerOff, FolderOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { FileTree } from "@/components/workspace/FileTree";
import { FileViewer } from "@/components/workspace/FileViewer";
import { ImageViewer } from "@/components/workspace/ImageViewer";
import { MediaViewer } from "@/components/workspace/MediaViewer";
import { BinaryViewer } from "@/components/workspace/BinaryViewer";
import {
  fetchWorkspace,
  fetchFileTree,
  fetchFileContent,
  activateWorkspace,
  deactivateWorkspace,
  type WorkspaceInfo,
  type FileTreeNode,
} from "@/lib/api/workspace";
import { getFileCategory, type FileCategory } from "@/lib/workspace-file-types";

function WorkspaceViewerContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const workspaceId = searchParams.get("id") ?? "";

  const [workspace, setWorkspace] = useState<WorkspaceInfo | null>(null);
  const [tree, setTree] = useState<FileTreeNode[]>([]);
  const [selectedPath, setSelectedPath] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState<string | null>(null);
  const [fileTotalLines, setFileTotalLines] = useState(0);
  const [fileLoading, setFileLoading] = useState(false);
  const [fileCategory, setFileCategory] = useState<FileCategory>("text");

  useEffect(() => {
    if (!workspaceId) {
      router.push("/workspace");
      return;
    }
    fetchWorkspace(workspaceId)
      .then(setWorkspace)
      .catch(() => router.push("/workspace"));

    fetchFileTree(workspaceId, ".", 2)
      .then(setTree)
      .catch((err) => console.error("Failed to load tree:", err));
  }, [workspaceId, router]);

  const handleSelectFile = useCallback(
    async (path: string) => {
      setSelectedPath(path);
      const category = getFileCategory(path);
      setFileCategory(category);

      if (category === "text") {
        setFileLoading(true);
        try {
          const data = await fetchFileContent(workspaceId, path);
          setFileContent(data.content);
          setFileTotalLines(data.total_lines);
        } catch (err) {
          console.error("Failed to load file:", err);
          setFileContent("Error: Could not load file");
          setFileTotalLines(0);
        } finally {
          setFileLoading(false);
        }
      } else {
        setFileContent(null);
        setFileTotalLines(0);
        setFileLoading(false);
      }
    },
    [workspaceId]
  );

  const handleToggleActive = useCallback(async () => {
    if (!workspace) return;
    try {
      if (workspace.is_active) {
        await deactivateWorkspace();
        setWorkspace((prev) => (prev ? { ...prev, is_active: false } : prev));
      } else {
        const updated = await activateWorkspace(workspaceId);
        setWorkspace(updated);
      }
    } catch (err) {
      console.error("Failed to toggle active:", err);
    }
  }, [workspace, workspaceId]);

  if (!workspace) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-muted-foreground text-xs font-mono uppercase tracking-widest animate-pulse">
          Loading...
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-background">
      {/* Toolbar */}
      <div className="flex items-center justify-between px-6 py-3 border-b border-foreground/5 bg-foreground/[0.02] backdrop-blur-xl shrink-0">
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9 rounded-full hover:bg-foreground/10"
            onClick={() => router.push("/workspace")}
          >
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div className="flex items-center gap-3">
            <div className="px-3 py-1 text-[9px] font-black uppercase tracking-[0.15em] rounded-full border bg-primary/10 border-primary/20 text-primary flex items-center gap-1.5">
              <FolderOpen className="w-3 h-3" />
              Workspace
            </div>
            <div>
              <h1 className="text-sm font-black uppercase tracking-widest text-foreground">
                {workspace.name}
              </h1>
              <p className="text-[10px] text-muted-foreground font-mono truncate max-w-[400px]">
                {workspace.path}
              </p>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            className={`h-9 gap-2 px-3.5 rounded-full border transition-all duration-200 ${
              workspace.is_active
                ? "border-emerald-500/20 bg-emerald-500/10 text-emerald-400 hover:bg-red-500/10 hover:text-red-400 hover:border-red-500/20"
                : "border-foreground/10 bg-foreground/[0.03] text-muted-foreground hover:text-emerald-400 hover:bg-emerald-500/10 hover:border-emerald-500/20"
            }`}
            onClick={handleToggleActive}
          >
            {workspace.is_active ? (
              <>
                <PowerOff className="w-4 h-4" />
                <span className="text-[10px] font-bold uppercase tracking-wider">Deactivate</span>
              </>
            ) : (
              <>
                <Power className="w-4 h-4" />
                <span className="text-[10px] font-bold uppercase tracking-wider">Set Active</span>
              </>
            )}
          </Button>
        </div>
      </div>

      {/* 2-panel layout */}
      <div className="flex flex-1 overflow-hidden">
        {/* Left: File Tree */}
        <div className="w-72 lg:w-80 border-r border-foreground/5 overflow-y-auto bg-foreground/[0.01]">
          <div className="px-4 py-3 border-b border-foreground/5">
            <span className="text-[9px] font-black uppercase tracking-[0.2em] text-muted-foreground/40">
              File Explorer
            </span>
          </div>
          <FileTree
            workspaceId={workspaceId}
            nodes={tree}
            onSelectFile={handleSelectFile}
            selectedPath={selectedPath ?? undefined}
          />
        </div>

        {/* Right: File Viewer */}
        <div className="flex-1 overflow-hidden">
          {!selectedPath || fileCategory === "text" ? (
            <FileViewer
              path={selectedPath}
              content={fileContent}
              totalLines={fileTotalLines}
              loading={fileLoading}
            />
          ) : fileCategory === "image" ? (
            <ImageViewer workspaceId={workspaceId} path={selectedPath} />
          ) : fileCategory === "video" ? (
            <MediaViewer workspaceId={workspaceId} path={selectedPath} type="video" />
          ) : fileCategory === "audio" ? (
            <MediaViewer workspaceId={workspaceId} path={selectedPath} type="audio" />
          ) : (
            <BinaryViewer workspaceId={workspaceId} path={selectedPath} />
          )}
        </div>
      </div>
    </div>
  );
}

export default function WorkspaceViewer() {
  return (
    <Suspense
      fallback={
        <div className="flex items-center justify-center h-full">
          <div className="text-muted-foreground text-xs font-mono uppercase tracking-widest animate-pulse">
            Loading...
          </div>
        </div>
      }
    >
      <WorkspaceViewerContent />
    </Suspense>
  );
}
