"use client";

import { useMemo, useCallback } from "react";
import { AlertTriangle } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useDashboard } from "@/hooks/useDashboard";
import { buildDashboardCards } from "@/utils/dashboard-utils";
import {
  DashboardCards,
  DashboardCardsSkeleton,
} from "@/components/dashboard/DashboardCards";
import { DashboardWidgetGrid } from "@/components/dashboard/DashboardWidgetGrid";
import { WidgetModal } from "@/components/dashboard/WidgetModal";
import type { WidgetItem } from "@/types/dashboard";

function normalizeDisplayName(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const cleaned = value.trim();
  if (!cleaned) return null;
  // Prevent showing IDs like "12345" in greeting.
  if (/^\d+$/.test(cleaned)) return null;
  return cleaned;
}

export default function DashboardPage() {
  const piePalette = useMemo(
    () => [
      "#4f46e5",
      "#ec4899",
      "#f97316",
      "#22c55e",
      "#0ea5e9",
      "#a855f7",
      "#facc15",
      "#f43f5e",
      "#14b8a6",
    ],
    []
  );

  const {
    apiData,
    apiError,
    widgetData,
    widgetError,
    allocationData,
    allocationError,
    allocationLoading,
    activeWidget,
    closeModal,
    dashboardAllocations,
    activeWidgets,
    allocationWidgets,
    modalChartData,
    isInitialLoading,
    saveWidgetOrder,
    refetchWidgets,
  } = useDashboard();

  const snapshotCards = useMemo(() => buildDashboardCards(apiData), [apiData]);

  const backendAllWidgets = widgetData?.widgets?.all ?? [];
  const selectedWidgetIds = useMemo(
    () => allocationWidgets.map((w) => w.widget_id),
    [allocationWidgets]
  );
  const assetWidgetIds = useMemo(
    () =>
      new Set(
        backendAllWidgets
          .filter((w) => w.file_path === "asset_allocation")
          .map((w) => w.widget_id)
      ),
    [backendAllWidgets]
  );
  const allWidgets = useMemo(
    () =>
      backendAllWidgets.filter((w) => w.file_path === "asset_allocation"),
    [backendAllWidgets]
  );

  const handleAddWidget = useCallback(
    async (widget: WidgetItem) => {
      await saveWidgetOrder([...selectedWidgetIds, widget.widget_id]);
      refetchWidgets();
    },
    [selectedWidgetIds, saveWidgetOrder, refetchWidgets]
  );

  const handleSaveOrder = useCallback(
    async (orderedIds: string[]) => {
      const orderedAssetIds = orderedIds.filter((id) => assetWidgetIds.has(id));
      if (orderedAssetIds.length > 0) {
        await saveWidgetOrder(orderedAssetIds);
      }
    },
    [assetWidgetIds, saveWidgetOrder]
  );

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return "Good morning";
    if (h < 17) return "Good afternoon";
    return "Good evening";
  })();
  const firstName = useMemo(() => {
    const user = widgetData?.user as Record<string, unknown> | undefined;
    if (!user) return null;

    const fullName = normalizeDisplayName(user.fullName);
    if (fullName) return fullName.split(" ")[0] ?? fullName;

    const first = normalizeDisplayName(user.first_name ?? user.firstName);
    const last = normalizeDisplayName(user.last_name ?? user.lastName);
    const combined = [first, last].filter(Boolean).join(" ").trim();
    if (combined) return combined.split(" ")[0] ?? combined;

    const customerName = normalizeDisplayName(
      user.customer_name ?? user.customerName ?? user.name
    );
    return customerName ? customerName.split(" ")[0] ?? customerName : null;
  }, [widgetData?.user]);
  const today = new Date().toLocaleDateString("en-US", {
    weekday: "long", month: "long", day: "numeric",
  });

  return (
    <>
      {/* The canvas was carrying four stacked decorative layers — a diagonal
          gradient, a radial gradient, an ASCII grid and a gradient-clipped
          heading. On a page whose whole job is legible numbers, they cost
          contrast and gained nothing, so the surface is plain now. */}
      <div className="min-h-screen bg-background">
        <div className="mx-auto w-full max-w-[1600px] px-4 pb-16 pt-6 sm:px-6 lg:pt-8">
          <header className="mb-6">
            <p className="oxy-eyebrow">{today}</p>
            <h1 className="mt-1 text-2xl font-semibold tracking-tight text-foreground lg:text-3xl">
              {firstName ? `${greeting}, ${firstName}` : greeting}
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Here is where your portfolio stands today.
            </p>
          </header>

          {(apiError || widgetError) && (
            <Alert variant="warning" className="mb-6" aria-live="polite">
              <AlertTriangle aria-hidden />
              <AlertTitle>Some data could not be loaded</AlertTitle>
              <AlertDescription>
                {apiError && <p className="break-words">Dashboard data: {apiError}</p>}
                {widgetError && <p className="break-words">Widgets: {widgetError}</p>}
              </AlertDescription>
            </Alert>
          )}

          {/* Skeleton tiles rather than a blocking overlay: the page frame,
              greeting and layout stay on screen and the content fills in. */}
          {isInitialLoading ? (
            <DashboardCardsSkeleton />
          ) : (
            <DashboardCards cards={snapshotCards} />
          )}

          {widgetData !== null && (
            <DashboardWidgetGrid
              widgets={activeWidgets}
              allocations={dashboardAllocations}
              currency={apiData?.data?.currency}
              piePalette={piePalette}
              allWidgets={allWidgets}
              selectedWidgetIds={selectedWidgetIds}
              onAddWidget={handleAddWidget}
              onSaveOrder={handleSaveOrder}
            />
          )}

          {activeWidget && (
            <WidgetModal
              widget={activeWidget}
              allocationData={allocationData}
              allocationError={allocationError}
              allocationLoading={allocationLoading}
              modalChartData={modalChartData}
              currency={apiData?.data?.currency}
              piePalette={piePalette}
              onClose={closeModal}
            />
          )}
        </div>
      </div>
    </>
  );
}
