"use client";

export type DashboardWidgetKind = "chart" | "card" | "table";
export type DashboardWidgetFamily = "signal" | "options" | "perps" | "composite";

export type DashboardWidget = {
  id: string;
  kind: DashboardWidgetKind;
  family: DashboardWidgetFamily;
  sourceId: string;
  title: string;
  filters: Record<string, string>;
  colSpan: number;
  rowSpan: number;
  order: number;
};

export type SavedDashboard = {
  id: string;
  name: string;
  widgets: DashboardWidget[];
};

const STORAGE_KEY = "uforia.custom-dashboards.v1";
const EVENT_NAME = "uforia:dashboards-updated";

function defaultDashboards(): SavedDashboard[] {
  return [{ id: "main", name: "Main", widgets: [] }];
}

function nextId(prefix: string) {
  return `${prefix}-${Math.random().toString(36).slice(2, 10)}`;
}

export function loadDashboards(): SavedDashboard[] {
  if (typeof window === "undefined") return defaultDashboards();
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return defaultDashboards();
    const parsed = JSON.parse(raw) as SavedDashboard[];
    if (!Array.isArray(parsed) || parsed.length === 0) return defaultDashboards();
    return parsed;
  } catch {
    return defaultDashboards();
  }
}

export function saveDashboards(dashboards: SavedDashboard[]) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(dashboards));
  window.dispatchEvent(new CustomEvent(EVENT_NAME));
}

export function createDashboard(name: string): SavedDashboard {
  return { id: nextId("dashboard"), name, widgets: [] };
}

export function appendWidget(
  dashboards: SavedDashboard[],
  widget: Omit<DashboardWidget, "id" | "order">,
  dashboardId?: string,
): SavedDashboard[] {
  const current = dashboards.length > 0 ? dashboards : defaultDashboards();
  const targetId = dashboardId ?? current[0].id;
  return current.map((dashboard) => {
    if (dashboard.id !== targetId) return dashboard;
    const maxOrder = dashboard.widgets.reduce((max, item) => Math.max(max, item.order), -1);
    return {
      ...dashboard,
      widgets: [
        ...dashboard.widgets,
        {
          ...widget,
          id: nextId("widget"),
          order: maxOrder + 1,
        },
      ],
    };
  });
}

export function addWidgetToDashboards(
  widget: Omit<DashboardWidget, "id" | "order">,
  dashboardId?: string,
) {
  const next = appendWidget(loadDashboards(), widget, dashboardId);
  saveDashboards(next);
}

export function dashboardEventName() {
  return EVENT_NAME;
}
