'use client';

import {use} from 'react';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Grid} from '@astryxdesign/core/Grid';
import {Badge} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
import {
  BreadcrumbItem,
  Breadcrumbs,
} from '@astryxdesign/core/Breadcrumbs';
import {PageHeader} from '@/shared/components/primitives/PageHeader';
import {MetricCard} from '@/shared/components/patterns/MetricCard';
import {ChartCard} from '@/shared/components/charts/ChartCard';
import {AreaChartView} from '@/shared/components/charts/AreaChartView';
import {BarChartView} from '@/shared/components/charts/BarChartView';
import {LineChartView} from '@/shared/components/charts/LineChartView';
import {HeatmapGrid} from '@/shared/components/charts/HeatmapGrid';
import {AsyncBoundary} from '@/shared/components/data/AsyncBoundary';
import {SkeletonMetricGrid} from '@/shared/components/patterns/LoadingState';
import {ActivityTimeline} from '@/features/dashboard/components/ActivityTimeline';
import {useMetricColumns} from '@/features/dashboard/components/KpiRow';
import {useResource} from '@/shared/hooks/useResource';
import {storeRepository} from '@/features/stores/repositories/storeRepository';
import {dashboardRepository} from '@/features/dashboard/repositories/dashboardRepository';
import {useWorkspace} from '@/shared/providers/WorkspaceProvider';
import {ScopeControls} from '@/shared/components/scope/ScopeControls';
import {ICONS} from '@/shared/utils/icons';
import {
  formatCompact,
  formatDayLabel,
  formatInrCompact,
  formatPct,
} from '@/shared/utils/format';
import type {StoreStatus} from '@/features/stores/types/store';

const STATUS: Record<
  StoreStatus,
  {label: string; variant: 'success' | 'warning' | 'error'}
> = {
  open: {label: 'Open', variant: 'success'},
  maintenance: {label: 'Maintenance', variant: 'warning'},
  closed: {label: 'Closed', variant: 'error'},
};

/**
 * One store's dashboard.
 *
 * Deliberately the SAME chart components as the main dashboard, scoped by the
 * route's storeId rather than the shared scope's. Building store-specific chart
 * variants would double the surface area and guarantee the two drift apart —
 * the only thing that differs here is which store the query asks about.
 */
export default function StoreDetailPage({
  params,
}: {
  params: Promise<{storeId: string}>;
}) {
  const {storeId} = use(params);
  const {range} = useWorkspace();
  const scope = {range, storeId};

  const store = useResource(storeRepository.byId(scope, storeId), {
    isEmpty: () => false,
  });
  const kpis = useResource(dashboardRepository.kpis(scope));
  const series = useResource(dashboardRepository.timeseries(scope));
  const peak = useResource(dashboardRepository.peakHours(scope));
  const activity = useResource(dashboardRepository.activity(scope));

  const columns = useMetricColumns();
  const name = store.data?.name ?? 'Store';

  return (
    <VStack gap={5}>
      <Breadcrumbs variant="supporting">
        <BreadcrumbItem href="/stores">Store</BreadcrumbItem>
        <BreadcrumbItem isCurrent>{name}</BreadcrumbItem>
      </Breadcrumbs>

      <PageHeader
        title={name}
        description={
          store.data
            ? `${store.data.staffCount} staff · ${formatPct(store.data.conversionPct)} conversion`
            : 'Loading store…'
        }
        // Store scope is the route here, so only the period is selectable.
        controls={<ScopeControls hasStore={false} />}
        actions={
          <HStack gap={2} vAlign="center">
            {store.data ? (
              <Badge
                variant={STATUS[store.data.status].variant}
                label={STATUS[store.data.status].label}
              />
            ) : null}
            <Button
              variant="secondary"
              size="sm"
              label="All stores"
              href="/stores"
            />
          </HStack>
        }
      />

      <AsyncBoundary
        resource={kpis}
        loading={<SkeletonMetricGrid columns={columns} />}
      >
        {(rows) => (
          <Grid columns={columns} gap={4}>
            {rows.map((k) => (
              <MetricCard
                key={k.id}
                label={k.label}
                value={k.value}
                format={k.unit === 'inr' ? formatInrCompact : formatCompact}
                icon={
                  k.id === 'visitors'
                    ? ICONS.visitors
                    : k.id === 'purchases'
                      ? ICONS.purchases
                      : k.id === 'revenue'
                        ? ICONS.revenue
                        : ICONS.activeRewards
                }
                deltaPct={k.deltaPct}
                isRiseGood={k.isRiseGood}
                trend={k.trend}
              />
            ))}
          </Grid>
        )}
      </AsyncBoundary>

      <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>

        <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'}]}
              reference={{y: 22, label: 'Network benchmark', tone: 'positive'}}
            />
          )}
        </ChartCard>

        <ChartCard
          title="Peak hours"
          subtitle="Where this store's week actually lands"
          resource={peak}
          height={200}
        >
          {(d) => <HeatmapGrid data={d} />}
        </ChartCard>
      </Grid>

      <ActivityTimeline resource={activity} limit={6} height={285} />
    </VStack>
  );
}
