"use client";

import { GripVertical } from "lucide-react";
import {
  Activity,
  ArrowLeftRight,
  BarChart3,
  Eye,
  Landmark,
  LayoutGrid,
  LineChart,
  PieChart,
  TrendingUp,
  Wallet,
  type LucideIcon,
} from "lucide-react";
import type { WidgetItem, DashboardAllocation } from "@/types/dashboard";
import { AllocationStateView } from "./AllocationStateView";
import { UsdEurWidget } from "./UsdEurWidget";
import { TickTapeWidget } from "./TickTapeWidget";
import { MarketOverviewFxWidget } from "./MarketOverviewFxWidget";
import { MarketOverviewIndicesWidget } from "./MarketOverviewIndicesWidget";
import { MarketOverviewStocksWidget } from "./MarketOverviewStocksWidget";
import { WatchlistWidget } from "./WatchlistWidget";
import { CashHoldingSummaryWidget } from "./CashHoldingSummaryWidget";
import { PastPerformanceWidget } from "./PastPerformanceWidget";
import { DepositSummaryWidget } from "./DepositSummaryWidget";

const WIDGET_CARD_CHART_HEIGHT = 260;
const WIDGET_CARD_PLACEHOLDER_HEIGHT = 180;

function normalizeWidgetFilePath(filePath: string): string {
  return filePath
    .trim()
    .toLowerCase()
    .replace(/[\s-]+/g, "_");
}

function getWidgetKind(filePath: string):
  | "asset_allocation"
  | "widget6"
  | "ticktape"
  | "market_overview_fx"
  | "market_overview_indices"
  | "market_overview_stocks"
  | "watchlist"
  | "cash_holding"
  | "past_performance"
  | "deposit"
  | "unknown" {
  const normalized = normalizeWidgetFilePath(filePath);
  if (normalized === "asset_allocation") return "asset_allocation";
  if (normalized === "widget6") return "widget6";
  if (normalized === "ticktape") return "ticktape";
  if (["market_overview_fx", "marketoverview_fx", "market_overview_forex"].includes(normalized)) {
    return "market_overview_fx";
  }
  if (
    ["market_overview_indices", "marketoverview_indices", "market_overview_index"].includes(
      normalized
    )
  ) {
    return "market_overview_indices";
  }
  if (["market_overview_stocks", "marketoverview_stocks", "market_overview_equities"].includes(normalized)) {
    return "market_overview_stocks";
  }
  if (normalized === "watchlist") return "watchlist";
  if (["cash_holding", "cash_holding_summary", "cash_holdings"].includes(normalized)) {
    return "cash_holding";
  }
  if (normalized === "past_performance") return "past_performance";
  if (["deposit", "deposits", "deposit_summary", "deposit_widget"].includes(normalized)) {
    return "deposit";
  }
  return "unknown";
}

/**
 * Widget identity glyph.
 *
 * This was a coloured dot in ten unrelated hues (violet, sky, amber, rose,
 * blue, teal, orange, indigo, cyan, emerald) — none of them from the palette,
 * and a bare dot carries no meaning anyway: you still have to read the title.
 * A lucide icon in muted ink says what the widget *is* at a glance and matches
 * how every other surface in the app labels things.
 */
const WIDGET_ICON: Record<string, LucideIcon> = {
  asset_allocation:        PieChart,
  widget6:                 ArrowLeftRight,
  ticktape:                Activity,
  market_overview_fx:      ArrowLeftRight,
  market_overview_indices: BarChart3,
  market_overview_stocks:  TrendingUp,
  watchlist:               Eye,
  cash_holding:            Wallet,
  past_performance:        LineChart,
  deposit:                 Landmark,
};

export interface WidgetCardContentProps {
  widget: WidgetItem;
  allocation: DashboardAllocation;
  currency?: string;
  piePalette: string[];
  /** Wired to useSortableGrid; omit to render a non-draggable card. */
  dragHandleProps?: {
    onPointerDown: (event: React.PointerEvent) => void;
    onKeyDown: (event: React.KeyboardEvent) => void;
    "aria-grabbed": boolean;
  };
  isDragging?: boolean;
  isKeyboardDragging?: boolean;
}

export function WidgetCardContent({
  widget,
  allocation,
  currency,
  piePalette,
  dragHandleProps,
  isDragging = false,
  isKeyboardDragging = false,
}: WidgetCardContentProps) {
  const widgetKind = getWidgetKind(widget.file_path);
  const isAssetAllocation = widgetKind === "asset_allocation";
  const displayTitle = isAssetAllocation ? "Asset Allocation" : widget.name || "Widget";
  const Icon = WIDGET_ICON[widgetKind] ?? LayoutGrid;

  return (
    /* rounded-lg to match the Card primitive used by the stat tiles — this was
       rounded-xl, so the two rows of cards on the dashboard had visibly
       different corners. */
    <div className="flex h-full flex-col overflow-hidden rounded-lg border border-border bg-card shadow-sm transition-shadow duration-200 hover:shadow-md">
      {/* Title bar doubles as the drag handle.
          Dragging is deliberately limited to the header rather than the whole
          card: the body hosts interactive TradingView embeds and charts, and a
          whole-card drag would swallow every click inside them. */}
      <div
        className={`flex shrink-0 items-center gap-2 border-b border-border px-4 py-2.5 ${
          isKeyboardDragging ? "bg-accent" : ""
        }`}
      >
        <Icon className="size-4 shrink-0 text-muted-foreground" aria-hidden />
        <p className="truncate text-sm font-semibold text-foreground">{displayTitle}</p>

        {dragHandleProps && (
          <button
            type="button"
            {...dragHandleProps}
            aria-label={`Reorder ${displayTitle}. Press Space to pick up, arrow keys to move, Space to drop.`}
            title="Drag to reorder"
            className={`-mr-1.5 ml-auto flex size-7 shrink-0 touch-none items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground ${
              isDragging ? "cursor-grabbing bg-muted text-foreground" : "cursor-grab"
            }`}
          >
            <GripVertical className="size-4" aria-hidden />
          </button>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-h-0 overflow-hidden">
        {isAssetAllocation ? (
          <AllocationStateView
            allocation={allocation}
            currency={currency}
            piePalette={piePalette}
            height={WIDGET_CARD_CHART_HEIGHT}
            widget={widget}
            placeholderMinHeight={WIDGET_CARD_PLACEHOLDER_HEIGHT}
          />
        ) : widgetKind === "widget6" ? (
          <UsdEurWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "ticktape" ? (
          <TickTapeWidget />
        ) : widgetKind === "market_overview_fx" ? (
          <MarketOverviewFxWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "market_overview_indices" ? (
          <MarketOverviewIndicesWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "market_overview_stocks" ? (
          <MarketOverviewStocksWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "watchlist" ? (
          <WatchlistWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "cash_holding" ? (
          <CashHoldingSummaryWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "past_performance" ? (
          <PastPerformanceWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : widgetKind === "deposit" ? (
          <DepositSummaryWidget height={WIDGET_CARD_CHART_HEIGHT} />
        ) : (
          /* Unknown widget kind — the file_path has no renderer yet. Reads as
             a deliberate placeholder now rather than a blank panel with the
             title repeated in the middle of it. */
          <div className="flex h-full min-h-[180px] flex-col items-center justify-center gap-1.5 px-6 text-center">
            <span
              className="mb-1 flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground"
              aria-hidden
            >
              <LayoutGrid className="size-4" />
            </span>
            <p className="text-sm font-medium text-foreground">Nothing to display</p>
            <p className="max-w-[15rem] text-xs leading-relaxed text-muted-foreground">
              {widget.short_description || "This widget has no data source connected yet."}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
