import { notFound } from "next/navigation";
import { Suspense } from "react";
import { getCurrentSession } from "@/lib/session";
import { parseDashboardLayout } from "@/lib/dashboard";
import { computeDefaultLayout } from "@/lib/dashboard.server";
import { getWidget, getWidgetMetas } from "@/modules/_core";
import { getDashboardBySlug } from "@/app/d/actions";
import { DashboardEditor } from "@/components/dashboard-editor";
import { EditDashboardButton } from "@/components/edit-dashboard-button";
import { DashboardSwitcher } from "@/components/dashboard-switcher";
import { DashboardTab } from "@/components/dashboard-tab";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
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",
};

const greetingForHour = (h: number) =>
  h < 5 ? "Up early" : h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening";

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 layout = parseDashboardLayout(dashboard.layout) ?? computeDefaultLayout();
  const widgetMetas = getWidgetMetas();

  if (isEditing) {
    return (
      <DashboardEditor
        dashboard={{ id: dashboard.id, name: dashboard.name, slug: dashboard.slug }}
        layout={layout}
        widgetMetas={widgetMetas}
      />
    );
  }

  // 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 greeting = greetingForHour(new Date().getHours());
  const today = new Date().toLocaleDateString(undefined, {
    weekday: "long",
    month: "long",
    day: "numeric",
  });
  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">
        <div>
          <h1 className="serif text-[26px] sm:text-[30px] leading-tight tracking-tight">
            {greeting}
            {firstName && `, ${firstName}`}.
          </h1>
          <p className="muted mt-1 text-[13px]">{today}</p>
        </div>
        <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="animate-pulse space-y-2">
                        <div className="h-3 w-3/4 rounded bg-muted" />
                        <div className="h-3 w-1/2 rounded bg-muted" />
                        <div className="h-3 w-2/3 rounded bg-muted" />
                      </div>
                    }
                  >
                    {widget.render({ config: placement.config, ctx })}
                  </Suspense>
                </CardContent>
              </Card>
            </div>
          );
        })}
      </div>
    </div>
  );
}
