import { notFound } from "next/navigation";
import { Suspense } from "react";
import { getCurrentSession } from "@/lib/session";
import { parseDashboardLayout, widgetContentIndexKey } from "@/lib/dashboard";
import { readEditorDraftLayout } from "@/lib/dashboard-editor-draft";
import { computeDefaultLayout, normalizeDashboardLayout } from "@/lib/dashboard.server";
import { getWidget, getWidgetMetas } from "@/modules/_core";
import { getDashboardBySlug } from "@/app/d/actions";
import { DashboardEditor } from "@/components/dashboard-editor";
import { DashboardWidgetContent } from "@/components/dashboard-widget-content";
import { EditDashboardButton } from "@/components/edit-dashboard-button";
import { DashboardSwitcher } from "@/components/dashboard-switcher";
import { DashboardTab } from "@/components/dashboard-tab";
import { DashboardGreeting } from "@/components/dashboard-greeting";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { dashboards } from "@/modules/_core/schema";
import { asc, eq } from "drizzle-orm";
import type { DashLayout } from "@/modules/_core/themes";

const smColSpan: Record<number, string> = {
  1: "sm:col-span-1",
  2: "sm:col-span-2",
  3: "sm:col-span-3",
  4: "sm:col-span-4",
  5: "sm:col-span-5",
  6: "sm:col-span-6",
  7: "sm:col-span-7",
  8: "sm:col-span-8",
  9: "sm:col-span-9",
  10: "sm:col-span-10",
  11: "sm:col-span-11",
  12: "sm:col-span-12",
};

export default async function DashboardPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ edit?: string }>;
}) {
  const { slug } = await params;
  const { edit } = await searchParams;
  const isEditing = edit === "1";

  const { user, household } = await getCurrentSession();
  const dashboard = await getDashboardBySlug(slug);
  if (!dashboard) notFound();

  const storedLayout = parseDashboardLayout(dashboard.layout) ?? computeDefaultLayout();
  const draftLayout = isEditing ? await readEditorDraftLayout(dashboard.id) : null;
  const layout = normalizeDashboardLayout(draftLayout ?? storedLayout);
  const widgetMetas = getWidgetMetas();

  if (isEditing) {
    const ctx = { userId: user.id, householdId: household.id };
    const widgetContents = Object.fromEntries(
      layout.widgets.map((placement, index) => [
        widgetContentIndexKey(index),
        <DashboardWidgetContent
          key={widgetContentIndexKey(index)}
          placement={placement}
          ctx={ctx}
        />,
      ]),
    );

    return (
      <DashboardEditor
        key={`${dashboard.id}:${JSON.stringify(layout.widgets)}`}
        dashboard={{ id: dashboard.id, name: dashboard.name, slug: dashboard.slug }}
        layout={layout}
        widgetMetas={widgetMetas}
        widgetContents={widgetContents}
      />
    );
  }

  // For dashboard tabs sub-header, pull the user's dashboards (small list).
  const session = await auth();
  const userDashboards = session?.user?.id
    ? await db
        .select({
          id: dashboards.id,
          name: dashboards.name,
          slug: dashboards.slug,
          isDefault: dashboards.isDefault,
          position: dashboards.position,
        })
        .from(dashboards)
        .where(eq(dashboards.userId, session.user.id))
        .orderBy(asc(dashboards.position), asc(dashboards.createdAt))
    : [];

  const ctx = { userId: user.id, householdId: household.id };
  const placements = [...layout.widgets].sort((a, b) => a.y - b.y || a.x - b.x);
  const dashLayout = (user.themeDashLayout as DashLayout) ?? "classic";
  const containerCls =
    dashLayout === "glance" ? "max-w-[760px] mx-auto" : dashLayout === "split" ? "" : "";
  const firstName = (user.name ?? "").split(" ")[0] ?? "";

  return (
    <div className={containerCls}>
      {userDashboards.length >= 1 && (
        <div className="flex items-center gap-1 mb-4 overflow-x-auto">
          {userDashboards.map((d) => (
            <DashboardTab key={d.id} slug={d.slug} name={d.name} />
          ))}
          <DashboardSwitcher dashboards={userDashboards} />
        </div>
      )}

      <div className="mb-6 flex items-end justify-between gap-4 flex-wrap">
        <DashboardGreeting firstName={firstName} />
        <EditDashboardButton />
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
        {placements.map((placement, i) => {
          const widget = getWidget(placement.widgetId);
          if (!widget) return null;
          const colClass = smColSpan[placement.w] ?? "sm:col-span-12";
          return (
            <div key={i} className={`col-span-1 ${colClass}`}>
              <Card className="h-full">
                <CardHeader>
                  <CardTitle>{widget.title}</CardTitle>
                </CardHeader>
                <CardContent>
                  <Suspense
                    fallback={
                      <div className="space-y-3">
                        <Skeleton className="h-4 w-3/4" />
                        <Skeleton className="h-4 w-1/2" />
                        <Skeleton className="h-4 w-2/3" />
                      </div>
                    }
                  >
                    {widget.render({ config: placement.config, ctx })}
                  </Suspense>
                </CardContent>
              </Card>
            </div>
          );
        })}
      </div>
    </div>
  );
}
