'use client';

import { useState } from 'react';

import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { PageHeader } from '@/components/shared/page-header';
import { KpiCardsWithBoundary } from './kpi-cards';
import { ActivityFeed } from './activity-feed';
import { DateRangePicker } from './date-range-picker';
import { PipelineFunnelChart } from './pipeline-funnel-chart';
import { OccupancyTimelineChart } from './occupancy-timeline-chart';
import { RevenueBreakdownChart } from './revenue-breakdown-chart';
import { LeadSourceChart } from './lead-source-chart';
import { WidgetErrorBoundary } from './widget-error-boundary';
import { AlertRail } from '@/components/alerts/alert-rail';
import type { DateRange } from '@/lib/services/analytics.service';

const RANGE_LABELS: Record<DateRange, string> = {
  today: 'Today',
  '7d': 'Last 7 days',
  '30d': 'Last 30 days',
  '90d': 'Last 90 days',
};

export function DashboardShell() {
  const [range, setRange] = useState<DateRange>('30d');

  useRealtimeInvalidation({
    'interest:stageChanged': [
      ['analytics', 'pipeline_funnel', range],
      ['analytics', 'lead_source_attribution', range],
      ['dashboard', 'kpis'],
    ],
    'client:created': [['dashboard', 'kpis']],
    'berth:statusChanged': [
      ['analytics', 'occupancy_timeline', range],
      ['dashboard', 'kpis'],
    ],
  });

  return (
    <div className="space-y-6">
      <PageHeader
        title="Dashboard"
        eyebrow="Overview"
        description="Live snapshot of your marina activity"
        kpiLine={<span>{RANGE_LABELS[range]}</span>}
        variant="gradient"
        actions={<DateRangePicker value={range} onChange={setRange} />}
      />

      <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
        <KpiCardsWithBoundary />
      </div>

      <div className="grid gap-4 grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px]">
        <div className="grid gap-4 grid-cols-1 lg:grid-cols-2">
          <WidgetErrorBoundary>
            <PipelineFunnelChart range={range} />
          </WidgetErrorBoundary>
          <WidgetErrorBoundary>
            <OccupancyTimelineChart range={range} />
          </WidgetErrorBoundary>
          <WidgetErrorBoundary>
            <RevenueBreakdownChart range={range} />
          </WidgetErrorBoundary>
          <WidgetErrorBoundary>
            <LeadSourceChart range={range} />
          </WidgetErrorBoundary>
        </div>
        <aside className="min-w-0">
          <WidgetErrorBoundary>
            <AlertRail />
          </WidgetErrorBoundary>
        </aside>
      </div>

      <ActivityFeed />
    </div>
  );
}
