import { AppSidebar } from "@/components/app-sidebar";
import { NavActions } from "@/components/nav-actions";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbList,
  BreadcrumbPage,
} from "@/components/ui/breadcrumb";

import { Separator } from "@/components/ui/separator";
import {
  SidebarInset,
  SidebarProvider,
  SidebarTrigger,
} from "@/components/ui/sidebar";
import { createClient } from "@/utils/supabase/server";
import { redirect } from "next/navigation";

import { TTSProvider } from "@/components/TTSProvider";
import MarkdownRenderer from "@/components/MarkdownRenderer";

export default async function DocumentPage(props: { params: { id: string } }) {
  const supabase = await createClient();

  const {
    data: { user },
    error: userError,
  } = await supabase.auth.getUser();

  if (userError) {
    console.error("Error fetching user:", userError);
  }

  if (!user) {
    return redirect("/login");
  }

  const { id } = await props.params;

  // Fetch the document details based on the ID from params
  const { data: document, error } = await supabase
    .from("documents")
    .select("*")
    .eq("id", id)
    .single();

  if (error || !document) {
    console.error("Error fetching document:", error);
  }

  // If the document doesn't exist, redirect to the documents page or handle it accordingly
  if (!document) {
    return redirect("/dashboard");
  }
  const { data: documents, error: documentsError } = await supabase
    .from("documents")
    .select("*")
    .eq("owner", user.id)
    .order("created_at", { ascending: false });

  if (documentsError) {
    console.error("Error fetching documents:", error);
    return <div>Error loading documents.</div>;
  }

  const pages = (document.ocr_data as any).map((page: any) => page.markdown);

  // Here we simply recreate the pages string:
  const rawContent =
    (document?.ocr_data as any)?.map((page: any) => page.markdown).join("\n") ||
    "";

  return (
    <SidebarProvider>
      <TTSProvider pages={pages}>
        <AppSidebar
          documents={documents.map((d) => {
            return {
              id: d.id,
              disabled: d.is_processing,
              name: d.file_name,
              url: `/dashboard/documents/${d.id}`,
              emoji: "📄",
            };
          })}
        />
        <SidebarInset>
          <header className="grid grid-cols-2 h-14 items-center gap-2 sticky top-0 right-0 w-full bg-background border-b border-slate-800 z-10">
            <div className="flex items-center gap-2 px-3">
              <SidebarTrigger />
              <Separator
                orientation="vertical"
                className="mr-2 data-[orientation=vertical]:h-4"
              />
              <Breadcrumb>
                <BreadcrumbList>
                  <BreadcrumbItem>
                    <BreadcrumbPage className="line-clamp-1">
                      {document.file_name || "Document Details"}
                    </BreadcrumbPage>
                  </BreadcrumbItem>
                </BreadcrumbList>
              </Breadcrumb>
            </div>
            <div className="flex items-center justify-end gap-2 px-3">
              <NavActions pages={pages} />
            </div>
          </header>
          {/* <div
          className="prose mx-auto px-4 py-10
                    text-white
                    prose-h1:font-semibold prose-h1:text-2xl prose-h1:mb-4 prose-h1:text-white
                    prose-h2:font-medium prose-h2:text-xl prose-h2:mb-3 prose-h2:text-white
                    prose-h3:font-medium prose-h3:text-lg prose-h3:mb-2 prose-h3:text-gray-300
                    prose-h4:font-medium prose-h4:text-lg prose-h4:mb-2 prose-h4:text-gray-300
                    prose-a:text-blue-400 hover:prose-a:underline
                    prose-p:leading-7 prose-p:text-gray-200
                    prose-strong:text-gray-200 prose-strong:font-semibold
                    prose-blockquote:italic prose-blockquote:border-l-4 prose-blockquote:pl-4 prose-blockquote:border-gray-600 prose-blockquote:text-gray-300
                    prose-code:bg-gray-800 prose-code:rounded prose-code:px-1 prose-code:py-0.5 prose-code:text-gray-200
                    prose-img:rounded-lg prose-img:shadow-sm"
          dangerouslySetInnerHTML={{ __html: String(processedContent) }}
        ></div> */}
          <div className="mx-auto px-12 py-20 gap-2">
            <MarkdownRenderer document={document} />
          </div>
        </SidebarInset>
      </TTSProvider>
    </SidebarProvider>
  );
}
