'use client';

import { useCurrentUser } from '@/features/auth/CurrentUser';
import { SavedReportWidget } from '@/features/saved-reports/ui/SavedReportWidget';
import { resolveDateRange, todayIn } from '../format';
import {
  DASHBOARD_GRID_COLUMNS,
  REPORT_LABEL,
  type ActivityReportGroupBy,
  type DashboardDateRange,
  type DashboardReportId,
  type DashboardReportWidget,
  type DashboardWidget,
  type ForecastPeriod,
  type SalesTargetPeriod,
  type SequenceReportGroupBy,
  type WorkflowReportGroupBy,
} from '../types';
import {
  ActivityPanel,
  ForecastPanel,
  PipelineByStagePanel,
  SequencesPanel,
  TargetsPanel,
  WonByMonthPanel,
  WorkflowsPanel,
} from './panels';

/** The range a report widget shows when its saved filters have none. */
export const DEFAULT_WIDGET_RANGE: Partial<Record<DashboardReportId, DashboardDateRange>> = {
  won_by_month: 'last_12_months',
  targets: 'this_quarter',
  activity: 'this_week',
  workflows: 'last_30_days',
  sequences: 'last_30_days',
};

/** Reports whose widget filters take a relative `dateRange`. */
export const takesDateRange = (reportId: DashboardReportId) => reportId in DEFAULT_WIDGET_RANGE;

/** One dashboard widget: its report, with the saved filters turned into a query. */
export function WidgetView({ widget }: { widget: DashboardReportWidget }) {
  const me = useCurrentUser();
  const f = widget.filters ?? {};
  // QA #376: a saved report runs its own definition.
  if (widget.reportId === 'saved_report') {
    return <SavedReportWidget savedReportId={f.savedReportId} title={widget.title} />;
  }
  const title = widget.title || REPORT_LABEL[widget.reportId];
  const preset = f.dateRange ?? DEFAULT_WIDGET_RANGE[widget.reportId] ?? 'this_month';
  const { from, to } = resolveDateRange(preset, todayIn(me.business.timezone));

  switch (widget.reportId) {
    case 'won_by_month':
      return (
        <WonByMonthPanel
          title={title}
          from={from}
          to={to}
          pipelineId={f.pipelineId}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    case 'pipeline_by_stage':
      return (
        <PipelineByStagePanel
          title={title}
          pipelineId={f.pipelineId}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    case 'forecast':
      return (
        <ForecastPanel
          title={title}
          period={(f.period as ForecastPeriod) || 'month'}
          pipelineId={f.pipelineId}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    case 'targets':
      return (
        <TargetsPanel
          title={title}
          from={from}
          to={to}
          period={(f.period as SalesTargetPeriod) || 'month'}
          type={f.type}
          assigneeId={f.assigneeId}
          assigneeIds={f.assigneeIds}
          teamIds={f.teamIds}
        />
      );
    case 'activity':
      return (
        <ActivityPanel
          title={title}
          from={from}
          to={to}
          groupBy={(f.groupBy as ActivityReportGroupBy) || 'user'}
          types={f.types}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    case 'workflows':
      return (
        <WorkflowsPanel
          title={title}
          from={from}
          to={to}
          groupBy={(f.groupBy as WorkflowReportGroupBy) || 'workflow'}
          workflowId={f.workflowId}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    case 'sequences':
      return (
        <SequencesPanel
          title={title}
          from={from}
          to={to}
          groupBy={(f.groupBy as SequenceReportGroupBy) || 'sequence'}
          sequenceId={f.sequenceId}
          ownerId={f.ownerId}
          ownerIds={f.ownerIds}
          teamIds={f.teamIds}
        />
      );
    default:
      return null;
  }
}

/** Widgets in reading order (top to bottom, then left to right). */
export function orderWidgets(widgets: DashboardWidget[]): DashboardWidget[] {
  return [...widgets].sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x);
}

/**
 * Lays widgets out again in the given order on the 12-column grid: left to right, a new row
 * when the next one does not fit. Keeps each widget's width and height.
 */
export function packWidgets(widgets: DashboardWidget[]): DashboardWidget[] {
  let x = 0;
  let y = 0;
  let rowHeight = 0;
  return widgets.map((w) => {
    const width = Math.min(Math.max(1, w.position.w), DASHBOARD_GRID_COLUMNS);
    const height = Math.max(1, w.position.h);
    if (x + width > DASHBOARD_GRID_COLUMNS) {
      y += rowHeight;
      x = 0;
      rowHeight = 0;
    }
    const placed = { ...w, position: { x, y, w: width, h: height } };
    x += width;
    rowHeight = Math.max(rowHeight, height);
    return placed;
  });
}
