'use client';

import {useState} from 'react';
import {VStack} from '@astryxdesign/core/Layout';
import {Grid} from '@astryxdesign/core/Grid';
import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {PageHeader} from '@/shared/components/primitives/PageHeader';
import {ScopeControls} from '@/shared/components/scope/ScopeControls';
import {ICONS} from '@/shared/utils/icons';
import {ChartCard} from '@/shared/components/charts/ChartCard';
import {AreaChartView} from '@/shared/components/charts/AreaChartView';
import {LineChartView} from '@/shared/components/charts/LineChartView';
import {BarChartView} from '@/shared/components/charts/BarChartView';
import {HeatmapGrid} from '@/shared/components/charts/HeatmapGrid';
import {KpiRow} from '@/features/dashboard/components/KpiRow';
import {ActivityTimeline} from '@/features/dashboard/components/ActivityTimeline';
import {RewardUsageChart} from '@/features/dashboard/components/RewardUsageChart';
import {StoreComparisonPanel} from '@/features/dashboard/components/StoreComparison';
import {PerformancePanel} from '@/features/dashboard/components/PerformancePanel';
import {
  useDashboardActivity,
  useDashboardKpis,
  useDashboardPeakHours,
  useDashboardRewardUsage,
  useDashboardStoreComparison,
  useDashboardTimeseries,
} from '@/features/dashboard/hooks/useDashboard';
import {useWorkspace} from '@/shared/providers/WorkspaceProvider';
import {useScopeLabel} from '@/features/stores/hooks/useStoreDirectory';
import {greetingFor} from '@/features/dashboard/services/dashboardService';
import type {Granularity} from '@/features/dashboard/types/dashboard';
import {
  formatCompact,
  formatDayLabel,
  formatInrCompact,
  formatPct,
} from '@/shared/utils/format';

/**
 * An analytics workspace. Charts are the subject, not evidence for a to-do list.
 *
 * The page reads top-down as one narrowing question: headline numbers → the two
 * trends that drive them → the conversion story behind those → when and on what
 * it happens → the period rollup → which store → what just happened.
 *
 * Operational widgets — quick actions, tasks, the AI briefing, top store/reward,
 * staff status — deliberately do NOT live here. The briefing endpoint they were
 * built on is still live and feeds Loyaly AI's AI tab, which is where that
 * class of content belongs: a panel you open to be told what to do, beside a
 * dashboard you read to work it out yourself.
 *
 * Recent activity keeps its compact form — six rows in a fixed box, full history
 * on /activity. The uncapped version reached 784px, taller than any chart on the
 * page, which is an operational log outweighing the analytics it sits among.
 *
 * Every panel is scoped by the same {storeId, range} from WorkspaceProvider, set
 * from this page's header. `series` is fetched once and shared by the four
 * charts drawn from it, so they cannot disagree.
 */

export default function DashboardPage() {
  const {storeId} = useWorkspace();
  const [granularity, setGranularity] = useState<Granularity>('weekly');
  // On by default: store comparison has always been part of the all-stores
  // dashboard, so Compare starts pressed and switches the panel off, rather
  // than hiding a panel that used to be there until someone finds the button.
  const [isComparing, setIsComparing] = useState(true);

  const kpis = useDashboardKpis();
  const series = useDashboardTimeseries();
  const peak = useDashboardPeakHours();
  const activity = useDashboardActivity();
  const rewards = useDashboardRewardUsage();
  const comparison = useDashboardStoreComparison();

  const isAllStores = storeId === 'all';
  const scopeLabel = useScopeLabel();

  return (
    <VStack gap={5}>
      {/* 1 + 2 — Sticky header: greeting, title, description, and filter controls. */}
      <div className="sticky -top-5 z-40 -mx-5 px-5 pt-5 pb-4 bg-[#0F0F10] border-b border-[#2F2F2F] shadow-sm">
        <PageHeader
          eyebrow={greetingFor(kpis.meta?.generatedAt)}
          title="Dashboard"
          description={`Business performance across ${scopeLabel}.`}
          controls={<ScopeControls />}
        />
      </div>

      {/* 3 — headline numbers. */}
      <KpiRow resource={kpis} />

      {/* 4 — primary analytics: the two series everything else explains. */}
      <Grid columns={{minWidth: 360, max: 2, repeat: 'fit'}} gap={4}>
        <ChartCard title="Footfall" subtitle="Visitors per day" resource={series}>
          {(d) => (
            <AreaChartView
              data={d}
              xKey="t"
              xFormat={formatDayLabel}
              yFormat={formatCompact}
              series={[{key: 'visitors', label: 'Visitors'}]}
            />
          )}
        </ChartCard>

        <ChartCard title="Revenue" subtitle="Daily takings" resource={series}>
          {(d) => (
            <BarChartView
              data={d}
              xKey="t"
              xFormat={formatDayLabel}
              yFormat={formatInrCompact}
              series={[{key: 'revenue', label: 'Revenue'}]}
            />
          )}
        </ChartCard>
      </Grid>

      {/* 5 — secondary analytics: the conversion story, in two readings. */}
      <Grid columns={{minWidth: 360, max: 2, repeat: 'fit'}} gap={4}>
        <ChartCard
          title="Visitors vs purchases"
          subtitle="The gap is the conversion opportunity"
          resource={series}
        >
          {(d) => (
            <LineChartView
              data={d}
              xKey="t"
              xFormat={formatDayLabel}
              yFormat={formatCompact}
              series={[
                {key: 'visitors', label: 'Visitors'},
                {key: 'purchases', label: 'Purchases'},
              ]}
            />
          )}
        </ChartCard>

        <ChartCard
          title="Conversion"
          subtitle="Share of visitors who bought"
          resource={series}
        >
          {(d) => (
            <LineChartView
              data={d}
              xKey="t"
              xFormat={formatDayLabel}
              yFormat={(v) => formatPct(v, 0)}
              series={[{key: 'conversion', label: 'Conversion'}]}
              // The only semantic colour on this chart: above the benchmark is
              // good, below is not, and that is what the tint communicates.
              reference={{y: 22, label: 'Network benchmark', tone: 'positive'}}
            />
          )}
        </ChartCard>
      </Grid>

      {/* 6 — operational analytics: when traffic lands, what it redeems. */}
      <Grid columns={{minWidth: 360, max: 2, repeat: 'fit'}} gap={4}>
        <ChartCard
          title="Peak hours"
          subtitle="Where the week's footfall actually lands"
          resource={peak}
          height={200}
        >
          {(d) => <HeatmapGrid data={d} />}
        </ChartCard>

        <RewardUsageChart resource={rewards} />
      </Grid>

      {/* 7 — period rollup. */}
      <PerformancePanel
        granularity={granularity}
        onGranularityChange={setGranularity}
      />

      {/* 8 — comparing stores is meaningless when scoped to one of them, which
             is why Compare is disabled rather than merely off in that case. */}
      {isAllStores && isComparing ? (
        <StoreComparisonPanel resource={comparison} />
      ) : null}

      {/* 9 — bounded feed: six rows, fixed box, full history on /activity. */}
      <ActivityTimeline
        resource={activity}
        subtitle="Latest events across the selected store and period"
        limit={6}
        height={285}
        viewAllHref="/activity"
      />
    </VStack>
  );
}
