"use client";

import { useMemo, useCallback } from "react";
import GlobalLoader from "@/components/ui/GlobalLoader";
import { useDashboard } from "@/hooks/useDashboard";
import { buildDashboardCards } from "@/utils/dashboard-utils";
import { DashboardCards } 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 (
    <>
      {isInitialLoading && <GlobalLoader />}
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-emerald-50/30 relative overflow-hidden">
        {/* Subtle background pattern */}
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-emerald-100/20 via-transparent to-transparent pointer-events-none" />
        <div className="absolute inset-0 ascii-grid opacity-30 pointer-events-none" />
        
        <div className="container mx-auto px-4 pb-16 pt-8 select-none animate-[fadeIn_0.7s_ease-in-out,slideUp_0.7s_ease-in-out] relative z-10">

          {/* Enhanced page header */}
          <div className="mb-8 flex items-end justify-between">
            <div className="space-y-2">
              <div className="flex items-center gap-3">
                <div className="h-px bg-gradient-to-r from-emerald-400 to-transparent w-12" />
                <p className="text-xs font-semibold uppercase tracking-widest text-emerald-600/70">{today}</p>
              </div>
              <h1 className="text-3xl md:text-4xl font-bold tracking-tight text-slate-900 bg-gradient-to-r from-slate-900 to-emerald-700 bg-clip-text text-transparent">
                {firstName ? `${greeting}, ${firstName}` : greeting}
              </h1>
              <p className="text-slate-600 text-sm">Welcome back to your financial overview</p>
            </div>
            <div className="hidden md:block">
              <div className="h-16 w-px bg-gradient-to-b from-transparent via-slate-200 to-transparent" />
            </div>
          </div>

        {(apiError || widgetError) && (
          <div
            className="mb-6 rounded-2xl border border-amber-200/50 bg-gradient-to-br from-amber-50/80 to-orange-50/80 backdrop-blur-sm px-5 py-4 text-xs text-amber-800 shadow-lg animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
            aria-live="polite"
          >
            <div className="flex items-start gap-3">
              <div className="flex-shrink-0 w-5 h-5 rounded-full bg-amber-200 flex items-center justify-center mt-0.5">
                <span className="text-amber-700 text-xs">⚠</span>
              </div>
              <div className="space-y-1">
                {apiError && <p className="font-medium">Dashboard data: {apiError}</p>}
                {widgetError && <p className="font-medium">Widgets: {widgetError}</p>}
              </div>
            </div>
          </div>
        )}

        <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>
    </>
  );
}
