"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";

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

  const {
    apiData,
    apiError,
    widgetData,
    widgetLoading,
    widgetError,
    activeWidget,
    setActiveWidget,
    allocationData,
    allocationError,
    dashboardAllocations,
    activeWidgets,
    allocationWidgets,
    modalChartData,
    isInitialLoading,
    closeModal,
    saveWidgetOrder,
  } = 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(
    (widget: WidgetItem) => {
      saveWidgetOrder([...selectedWidgetIds, widget.widget_id]);
    },
    [selectedWidgetIds, saveWidgetOrder]
  );

  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 = widgetData?.user?.fullName?.split(" ")[0] ?? null;
  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}` : "Dashboard"}
              </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} />

        {!widgetLoading && (
          <DashboardWidgetGrid
            widgets={allocationWidgets}
            allocations={dashboardAllocations}
            currency={apiData?.data?.currency}
            piePalette={piePalette}
            allWidgets={allWidgets}
            selectedWidgetIds={selectedWidgetIds}
            onAddWidget={handleAddWidget}
            onSaveOrder={handleSaveOrder}
            onOpenModal={setActiveWidget}
          />
        )}

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