"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Search, FileCode2, ChevronRight, Home } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { PageRow } from "@/components/pages/PageRow";
import { AddPageDialog } from "@/components/pages/AddPageDialog";
import {
  fetchPages,
  fetchBreadcrumb,
  deletePage,
  updatePage,
  uploadPage,
  uploadBundle,
  importPageFromPath,
  createBookmark,
  createFolder,
  type PageInfo,
} from "@/lib/api/pages";

export default function PagesDashboard() {
  const router = useRouter();
  const [pages, setPages] = useState<PageInfo[]>([]);
  const [search, setSearch] = useState("");
  const [currentFolderId, setCurrentFolderId] = useState<string | null>(null);
  const [breadcrumb, setBreadcrumb] = useState<PageInfo[]>([]);
  const [childCounts, setChildCounts] = useState<Record<string, number>>({});

  const refresh = useCallback(async () => {
    try {
      const pagesData = await fetchPages(currentFolderId);
      setPages(pagesData);

      // Fetch child counts for folders
      const folders = pagesData.filter((p) => p.content_type === "folder");
      if (folders.length > 0) {
        const counts: Record<string, number> = {};
        await Promise.all(
          folders.map(async (f) => {
            const children = await fetchPages(f.id);
            counts[f.id] = children.length;
          })
        );
        setChildCounts(counts);
      } else {
        setChildCounts({});
      }

      // Fetch breadcrumb
      if (currentFolderId) {
        const crumbs = await fetchBreadcrumb(currentFolderId);
        setBreadcrumb(crumbs);
      } else {
        setBreadcrumb([]);
      }
    } catch (err) {
      console.error("Failed to fetch data:", err);
    }
  }, [currentFolderId]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  const filteredPages = pages.filter((p) =>
    p.name.toLowerCase().includes(search.toLowerCase()) ||
    p.description.toLowerCase().includes(search.toLowerCase())
  );

  // Sort: folders first, then by name
  const sortedPages = [...filteredPages].sort((a, b) => {
    if (a.content_type === "folder" && b.content_type !== "folder") return -1;
    if (a.content_type !== "folder" && b.content_type === "folder") return 1;
    return a.name.localeCompare(b.name);
  });

  const handleNavigate = (id: string) => {
    const page = pages.find((p) => p.id === id);
    if (page?.content_type === "folder") {
      setCurrentFolderId(id);
      setSearch("");
    } else {
      router.push(`/pages/viewer?id=${id}`);
    }
  };

  const handleRename = async (id: string, name: string) => {
    await updatePage(id, { name });
    await refresh();
  };

  const handleDelete = async (id: string) => {
    await deletePage(id);
    await refresh();
  };

  const handleUpload = async (file: File, name: string, description: string, parentId?: string) => {
    await uploadPage(file, name, description, parentId);
    await refresh();
  };

  const handleUploadBundle = async (files: File[], name: string, description: string, parentId?: string) => {
    await uploadBundle(files, name, description, parentId);
    await refresh();
  };

  const handleImportPath = async (path: string, name: string, description: string, parentId?: string) => {
    await importPageFromPath(path, name, description, parentId);
    await refresh();
  };

  const handleCreateBookmark = async (name: string, url: string, description: string, parentId?: string) => {
    await createBookmark(name, url, description, parentId);
    await refresh();
  };

  const handleCreateFolder = async (name: string, description: string, parentId?: string) => {
    await createFolder(name, description, parentId);
    await refresh();
  };

  return (
    <div className="h-full overflow-y-auto p-10 space-y-12 bg-background relative">
      <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />

      <div className="relative flex flex-col gap-4">
        <div className="flex items-center gap-4">
          <div className="w-2 h-10 bg-primary" />
          <h1 className="text-4xl font-black uppercase tracking-tighter text-foreground">Custom Pages</h1>
        </div>
        <p className="text-muted-foreground text-sm font-bold uppercase tracking-[0.1em] ml-6">
          HTML Page & URL Bookmark Registry
        </p>
      </div>

      <div className="relative flex items-center justify-between gap-6 bg-card/50 p-6 border-2 border-border shadow-sm">
        <div className="relative flex-1 max-w-xl">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-primary" />
          <Input
            placeholder="SEARCH PAGE NAME OR DESCRIPTION..."
            className="pl-12 h-12 rounded-none bg-background border-2 border-border focus-visible:ring-primary focus-visible:border-primary font-mono text-xs uppercase"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        <div className="flex gap-4">
          <AddPageDialog
            currentFolderId={currentFolderId}
            onUpload={handleUpload}
            onUploadBundle={handleUploadBundle}
            onImportPath={handleImportPath}
            onCreateBookmark={handleCreateBookmark}
            onCreateFolder={handleCreateFolder}
          />
        </div>
      </div>

      {/* Breadcrumb navigation */}
      <div className="relative flex items-center gap-1.5 text-sm">
        <button
          onClick={() => { setCurrentFolderId(null); setSearch(""); }}
          className={`flex items-center gap-1.5 px-3 py-1.5 font-bold uppercase tracking-wider text-[11px] transition-colors ${
            !currentFolderId
              ? "text-primary"
              : "text-muted-foreground hover:text-foreground"
          }`}
        >
          <Home className="w-3.5 h-3.5" />
          Root
        </button>
        {breadcrumb.map((crumb) => (
          <div key={crumb.id} className="flex items-center gap-1.5">
            <ChevronRight className="w-3.5 h-3.5 text-muted-foreground/30" />
            <button
              onClick={() => { setCurrentFolderId(crumb.id); setSearch(""); }}
              className={`px-3 py-1.5 font-bold uppercase tracking-wider text-[11px] transition-colors ${
                crumb.id === currentFolderId
                  ? "text-primary"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {crumb.name}
            </button>
          </div>
        ))}
      </div>

      {/* Pages list */}
      <div className="relative border-2 border-border bg-card/30">
        {sortedPages.map((page) => (
          <PageRow
            key={page.id}
            page={page}
            childCount={page.content_type === "folder" ? childCounts[page.id] : undefined}
            onNavigate={handleNavigate}
            onRename={handleRename}
            onDelete={handleDelete}
          />
        ))}
        {sortedPages.length === 0 && (
          <div className="py-24 text-center flex flex-col items-center gap-4">
            <div className="p-4 bg-muted/20 border border-muted/30">
              <FileCode2 className="w-10 h-10 text-muted-foreground/30" />
            </div>
            <div className="space-y-1">
              <p className="text-muted-foreground font-bold uppercase tracking-widest">
                {currentFolderId ? "This Folder Is Empty" : "No Pages Registered"}
              </p>
              <p className="text-[10px] text-muted-foreground/50 uppercase font-mono italic">
                {currentFolderId
                  ? "Add a page or folder to get started."
                  : "Upload an HTML file or add a URL bookmark to get started."}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
