'use client';

import {VStack} from '@astryxdesign/core/Layout';
import {Grid} from '@astryxdesign/core/Grid';
import {PageHeader} from '@/shared/components/primitives/PageHeader';
import {ChartCard} from '@/shared/components/charts/ChartCard';
import {BarChartView} from '@/shared/components/charts/BarChartView';
import {StaffKpis} from '@/features/staff/components/StaffKpis';
import {StaffGrid} from '@/features/staff/components/StaffGrid';
import {AttendanceChart} from '@/features/staff/components/AttendanceChart';
import {Leaderboard} from '@/features/staff/components/Leaderboard';
import {
  useStaffAttendance,
  useStaffList,
  useStaffSummary,
} from '@/features/staff/hooks/useStaff';
import {useScopeLabel} from '@/features/stores/hooks/useStoreDirectory';
import {ScopeControls} from '@/shared/components/scope/ScopeControls';
import {formatCompact} from '@/shared/utils/format';

/**
 * The team.
 *
 * Ordered attendance-first: the question that brings a merchant here in the
 * morning is "who is in today", and only then "who is performing".
 */
export default function StaffPage() {
  const summary = useStaffSummary();
  const staff = useStaffList();
  const attendance = useStaffAttendance();
  const scopeLabel = useScopeLabel();

  return (
    <VStack gap={5}>
      <PageHeader
        title="Leaderboard"
        description={`Attendance, sales contribution and performance across ${scopeLabel}.`}
        controls={<ScopeControls />}
      />

      <StaffKpis resource={summary} />

      <Grid columns={{minWidth: 360, max: 2, repeat: 'fit'}} gap={4}>
        <AttendanceChart resource={attendance} />

        <ChartCard
          title="Sales by team member"
          subtitle="Top 8 by transactions in the selected period"
          resource={staff}
        >
          {(rows) => (
            <BarChartView
              data={[...rows]
                .sort((a, b) => b.salesCount - a.salesCount)
                .slice(0, 8)
                .map((m) => ({
                  // First name only — full names overflow the axis at this
                  // width and the leaderboard below carries the detail.
                  name: m.name.split(' ')[0],
                  sales: m.salesCount,
                  rewards: m.rewardsIssued,
                }))}
              xKey="name"
              yFormat={formatCompact}
              series={[
                {key: 'sales', label: 'Sales'},
                {key: 'rewards', label: 'Rewards issued'},
              ]}
            />
          )}
        </ChartCard>
      </Grid>

      <Leaderboard resource={staff} />

      <StaffGrid resource={staff} />
    </VStack>
  );
}
