"use client";

import { useEffect, useState, useCallback, Suspense } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";

// ── Types ─────────────────────────────────────────────────────────────────────

interface FileItem {
  name: string;
  path: string;
  type: "file" | "dir" | "symlink";
  size?: number;
}

interface TreeNode {
  name: string;
  path: string;
  type: "file" | "dir";
  children?: TreeNode[];
  expanded?: boolean;
  loaded?: boolean;
}

// ── Language detection ────────────────────────────────────────────────────────

function langFromName(name: string): string {
  const ext = name.split(".").pop()?.toLowerCase() ?? "";
  const map: Record<string, string> = {
    ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript",
    json: "json", md: "markdown", mdx: "markdown",
    css: "css", scss: "css", html: "html",
    py: "python", sh: "shell", yaml: "yaml", yml: "yaml",
    toml: "toml", prisma: "prisma", sql: "sql",
    env: "dotenv", gitignore: "shell", dockerfile: "dockerfile",
  };
  return map[ext] ?? "text";
}

// ── Simple token highlighter ──────────────────────────────────────────────────

function highlightCode(code: string, lang: string): React.ReactNode[] {
  return code.split("\n").map((line, i) => {
    if (lang === "text" || lang === "dotenv" || lang === "dockerfile") {
      return <div key={i}>{line || "\u00a0"}</div>;
    }
    const commentPrefixes = ["//", "#", "--"];
    if (commentPrefixes.some(p => line.trimStart().startsWith(p))) {
      return <div key={i}><span style={{ color: "#6a9955" }}>{line}</span></div>;
    }
    const kwRe = /\b(import|export|from|const|let|var|function|return|if|else|async|await|type|interface|class|extends|implements|new|default|null|undefined|true|false|void|string|number|boolean|object|Promise|React)\b/g;
    const parts = line.split(kwRe);
    const tokens = parts.map((part, j) => {
      if (!part) return null;
      if (/^(import|export|from|const|let|var|function|return|if|else|async|await|type|interface|class|extends|implements|new|default|null|undefined|true|false|void|string|number|boolean|object|Promise|React)$/.test(part)) {
        return <span key={j} style={{ color: "#569cd6" }}>{part}</span>;
      }
      if (/^(['"`]).*\1$/.test(part.trim())) {
        return <span key={j} style={{ color: "#ce9178" }}>{part}</span>;
      }
      return <span key={j}>{part}</span>;
    });
    return <div key={i} style={{ minHeight: "1.4em" }}>{tokens.length ? tokens : "\u00a0"}</div>;
  });
}

// ── Tree row ──────────────────────────────────────────────────────────────────

function TreeRow({
  node, depth, selectedPath, onSelect, onToggle,
}: {
  node: TreeNode;
  depth: number;
  selectedPath: string | null;
  onSelect: (path: string) => void;
  onToggle: (path: string) => void;
}) {
  const isSelected = selectedPath === node.path;
  const isDir = node.type === "dir";
  const ext = node.name.split(".").pop()?.toLowerCase() ?? "";
  const fileColor =
    ext === "tsx" || ext === "ts" ? "#3178c6"
    : ext === "jsx" || ext === "js" ? "#f0db4f"
    : ext === "css" || ext === "scss" ? "#e879f9"
    : ext === "json" ? "#a09a90"
    : ext === "md" || ext === "mdx" ? "#6b6560"
    : "#b5b0a6";

  return (
    <>
      <button
        onClick={() => isDir ? onToggle(node.path) : onSelect(node.path)}
        style={{
          display: "flex", alignItems: "center", gap: 6,
          width: "100%", textAlign: "left",
          background: isSelected ? "#f0ece4" : "transparent",
          border: "none", cursor: "pointer",
          padding: `5px 10px 5px ${14 + depth * 14}px`,
          borderRadius: 4, transition: "background 0.1s",
          fontFamily: "IBM Plex Mono, monospace", fontSize: "0.75rem",
          color: isSelected ? "#1a1a1a" : "#4a4640",
        }}
        onMouseEnter={e => { if (!isSelected) (e.currentTarget as HTMLElement).style.background = "#f6f4f0"; }}
        onMouseLeave={e => { if (!isSelected) (e.currentTarget as HTMLElement).style.background = "transparent"; }}
      >
        {isDir ? (
          <span style={{
            fontSize: "0.52rem", color: "#a09a90", flexShrink: 0,
            display: "inline-block", transition: "transform 0.12s",
            transform: node.expanded ? "rotate(90deg)" : "none",
          }}>▶</span>
        ) : (
          <span style={{ color: fileColor, fontSize: "0.7rem", flexShrink: 0 }}>◌</span>
        )}
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {node.name}
        </span>
      </button>
      {isDir && node.expanded && node.children?.map(child => (
        <TreeRow
          key={child.path}
          node={child}
          depth={depth + 1}
          selectedPath={selectedPath}
          onSelect={onSelect}
          onToggle={onToggle}
        />
      ))}
    </>
  );
}

// ── Empty state ───────────────────────────────────────────────────────────────

function EmptyState() {
  return (
    <div style={{
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      height: "100%", gap: 12, padding: 40,
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 12, background: "#f0ece4",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: "1.4rem", color: "#b5b0a6",
      }}>▢</div>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "0.88rem", fontWeight: 600, color: "#1a1a1a", marginBottom: 6 }}>
          Select an app to browse
        </div>
        <div style={{ fontSize: "0.78rem", color: "#a09a90", maxWidth: 260, lineHeight: 1.5 }}>
          Choose one of your apps from the Build section in the left sidebar to explore its files.
        </div>
      </div>
    </div>
  );
}

// ── Inner page (needs useSearchParams) ───────────────────────────────────────

function BuildPageInner() {
  const params = useParams();
  const searchParams = useSearchParams();
  const projectId = params.projectId as string;
  const { status: authStatus } = useSession();

  // Which app the user clicked (from sidebar link)
  const appName = searchParams.get("app") ?? "";
  const rootPath = searchParams.get("root") ?? "";

  const [tree, setTree] = useState<TreeNode[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [treeError, setTreeError] = useState<string | null>(null);
  const [selectedPath, setSelectedPath] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState<string | null>(null);
  const [fileLoading, setFileLoading] = useState(false);
  const [fileName, setFileName] = useState<string | null>(null);

  const fetchDir = useCallback(async (path: string): Promise<TreeNode[]> => {
    const res = await fetch(`/api/projects/${projectId}/file?path=${encodeURIComponent(path)}`);
    const data = await res.json();
    if (!res.ok) throw new Error(data.error ?? "Failed to load");
    const items: FileItem[] = data.items ?? [];
    return items
      .filter(item => item.type !== "symlink")
      .sort((a, b) => {
        if (a.type === "dir" && b.type !== "dir") return -1;
        if (a.type !== "dir" && b.type === "dir") return 1;
        return a.name.localeCompare(b.name);
      })
      .map(item => ({
        name: item.name,
        path: item.path,
        type: item.type === "dir" ? "dir" : "file",
        expanded: false,
        loaded: item.type !== "dir",
        children: item.type === "dir" ? [] : undefined,
      }));
  }, [projectId]);

  // Load the app's root dir whenever app changes
  useEffect(() => {
    if (!rootPath || authStatus !== "authenticated") return;
    setTree([]);
    setSelectedPath(null);
    setFileContent(null);
    setTreeError(null);
    setTreeLoading(true);
    fetchDir(rootPath)
      .then(nodes => { setTree(nodes); setTreeLoading(false); })
      .catch(e => { setTreeError(e.message); setTreeLoading(false); });
  }, [rootPath, authStatus, fetchDir]);

  // Toggle dir expand/collapse with lazy-load
  const handleToggle = useCallback(async (path: string) => {
    setTree(prev => {
      const toggle = (nodes: TreeNode[]): TreeNode[] =>
        nodes.map(n => {
          if (n.path === path) return { ...n, expanded: !n.expanded };
          if (n.children) return { ...n, children: toggle(n.children) };
          return n;
        });
      return toggle(prev);
    });

    const findNode = (nodes: TreeNode[], p: string): TreeNode | null => {
      for (const n of nodes) {
        if (n.path === p) return n;
        if (n.children) { const f = findNode(n.children, p); if (f) return f; }
      }
      return null;
    };

    const node = findNode(tree, path);
    if (node && !node.loaded) {
      try {
        const children = await fetchDir(path);
        setTree(prev => {
          const update = (nodes: TreeNode[]): TreeNode[] =>
            nodes.map(n => {
              if (n.path === path) return { ...n, children, loaded: true };
              if (n.children) return { ...n, children: update(n.children) };
              return n;
            });
          return update(prev);
        });
      } catch { /* silently fail */ }
    }
  }, [tree, fetchDir]);

  // Select a file and load its content
  const handleSelectFile = useCallback(async (path: string) => {
    setSelectedPath(path);
    setFileContent(null);
    setFileName(path.split("/").pop() ?? null);
    setFileLoading(true);
    try {
      const res = await fetch(`/api/projects/${projectId}/file?path=${encodeURIComponent(path)}`);
      const data = await res.json();
      setFileContent(data.content ?? "");
    } catch {
      setFileContent("// Failed to load file content");
    } finally {
      setFileLoading(false);
    }
  }, [projectId]);

  const lang = fileName ? langFromName(fileName) : "text";
  const lines = (fileContent ?? "").split("\n");

  if (!appName || !rootPath) {
    return <EmptyState />;
  }

  return (
    <div style={{ display: "flex", height: "100%", overflow: "hidden" }}>

      {/* ── File tree ── */}
      <div style={{
        width: 230, flexShrink: 0,
        borderRight: "1px solid #e8e4dc",
        background: "#faf8f5",
        display: "flex", flexDirection: "column",
        overflow: "hidden",
      }}>
        {/* App name header */}
        <div style={{
          padding: "11px 14px 10px",
          borderBottom: "1px solid #e8e4dc",
          display: "flex", alignItems: "center", gap: 8, flexShrink: 0,
        }}>
          <span style={{ fontSize: "0.72rem", color: "#a09a90" }}>▢</span>
          <span style={{ fontSize: "0.78rem", fontWeight: 600, color: "#1a1a1a", fontFamily: "Outfit, sans-serif" }}>
            {appName}
          </span>
        </div>

        {/* Tree */}
        <div style={{ flex: 1, overflow: "auto", padding: "6px 4px" }}>
          {treeLoading && (
            <div style={{ padding: "16px 14px", fontSize: "0.75rem", color: "#b5b0a6", fontFamily: "Outfit, sans-serif" }}>Loading…</div>
          )}
          {treeError && (
            <div style={{ padding: "16px 14px", fontSize: "0.75rem", color: "#e53e3e", fontFamily: "Outfit, sans-serif" }}>{treeError}</div>
          )}
          {!treeLoading && !treeError && tree.length === 0 && (
            <div style={{ padding: "16px 14px", fontSize: "0.75rem", color: "#b5b0a6", fontFamily: "Outfit, sans-serif" }}>Empty folder.</div>
          )}
          {tree.map(node => (
            <TreeRow
              key={node.path}
              node={node}
              depth={0}
              selectedPath={selectedPath}
              onSelect={handleSelectFile}
              onToggle={handleToggle}
            />
          ))}
        </div>
      </div>

      {/* ── Code preview ── */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "#1e1e1e", overflow: "hidden" }}>

        {/* Breadcrumb bar */}
        <div style={{
          padding: "10px 20px",
          borderBottom: "1px solid #2d2d2d",
          background: "#252526",
          display: "flex", alignItems: "center", gap: 8, flexShrink: 0,
        }}>
          {selectedPath ? (
            <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: "0.73rem", color: "#a09a90" }}>
              {/* Show path relative to rootPath */}
              {(() => {
                const rel = selectedPath.startsWith(rootPath + "/")
                  ? selectedPath.slice(rootPath.length + 1)
                  : selectedPath;
                return rel.split("/").map((seg, i, arr) => (
                  <span key={i}>
                    {i > 0 && <span style={{ color: "#555", margin: "0 4px" }}>/</span>}
                    <span style={{ color: i === arr.length - 1 ? "#d4d4d4" : "#888" }}>{seg}</span>
                  </span>
                ));
              })()}
            </span>
          ) : (
            <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: "0.73rem", color: "#555" }}>
              Select a file to view
            </span>
          )}
          {fileName && (
            <span style={{ marginLeft: "auto", fontFamily: "IBM Plex Mono, monospace", fontSize: "0.63rem", color: "#555", textTransform: "uppercase" }}>
              {lang}
            </span>
          )}
        </div>

        {/* Code area */}
        <div style={{ flex: 1, overflow: "auto", display: "flex" }}>
          {!selectedPath && !fileLoading && (
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", width: "100%", color: "#555", fontSize: "0.8rem", fontFamily: "IBM Plex Mono, monospace" }}>
              Select a file from the tree
            </div>
          )}
          {fileLoading && (
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", width: "100%", color: "#555", fontSize: "0.8rem", fontFamily: "IBM Plex Mono, monospace" }}>
              Loading…
            </div>
          )}
          {!fileLoading && fileContent !== null && (
            <div style={{ display: "flex", width: "100%", overflow: "auto" }}>
              {/* Line numbers */}
              <div style={{
                padding: "16px 0", background: "#1e1e1e",
                borderRight: "1px solid #2d2d2d",
                textAlign: "right", userSelect: "none", flexShrink: 0, minWidth: 44,
              }}>
                {lines.map((_, i) => (
                  <div key={i} style={{
                    fontFamily: "IBM Plex Mono, monospace", fontSize: "0.73rem",
                    lineHeight: "1.4em", color: "#555", padding: "0 12px 0 8px",
                  }}>
                    {i + 1}
                  </div>
                ))}
              </div>
              {/* Code */}
              <div style={{
                padding: "16px 24px",
                fontFamily: "IBM Plex Mono, monospace", fontSize: "0.73rem",
                lineHeight: "1.4em", color: "#d4d4d4",
                flex: 1, whiteSpace: "pre", overflow: "auto",
              }}>
                {highlightCode(fileContent, lang)}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Page export (Suspense wraps useSearchParams) ──────────────────────────────

export default function BuildPage() {
  return (
    <Suspense fallback={<div style={{ display: "flex", height: "100%", alignItems: "center", justifyContent: "center", color: "#a09a90", fontFamily: "Outfit, sans-serif", fontSize: "0.85rem" }}>Loading…</div>}>
      <BuildPageInner />
    </Suspense>
  );
}
