'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { initials } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';

// ---- Types ----------------------------------------------------------------

type Period = 'this_month' | 'this_year' | 'lifetime';
type Metric = 'km' | 'count';

interface LeaderboardRow {
  userId: number;
  fullName: string;
  viharCount: number;
  totalKm: number;
}

// ---- Page -----------------------------------------------------------------

const PERIOD_CHIPS: { label: string; value: Period }[] = [
  { label: 'This Month', value: 'this_month' },
  { label: 'This Year', value: 'this_year' },
  { label: 'Lifetime', value: 'lifetime' },
];

const METRIC_CHIPS: { label: string; value: Metric }[] = [
  { label: 'By km', value: 'km' },
  { label: 'By count', value: 'count' },
];

export default function LeaderboardPage() {
  const { data: me } = useMe();
  const [period, setPeriod] = useState<Period>('this_month');
  const [metric, setMetric] = useState<Metric>('km');

  const { data: rows, isLoading } = useQuery<LeaderboardRow[]>({
    queryKey: ['leaderboard', period, metric],
    queryFn: () =>
      api.get<LeaderboardRow[]>('/api/stats/leaderboard', { query: { period, metric } }),
    staleTime: 60 * 1000,
  });

  const myRow = rows?.find((r) => r.userId === me?.userId);
  const myRank = rows ? rows.findIndex((r) => r.userId === me?.userId) + 1 : 0;
  const showMyRow = myRank > 10 && myRow;

  return (
    <div className="space-y-4 pb-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Top Sevaks</h1>
      </div>

      {/* Period chips */}
      <div className="flex flex-wrap gap-2">
        {PERIOD_CHIPS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => setPeriod(value)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              period === value ? 'bg-ink text-paper' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Metric chips */}
      <div className="flex gap-2">
        {METRIC_CHIPS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => setMetric(value)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              metric === value ? 'bg-saffron text-white' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {isLoading && <p className="py-8 text-center text-sm text-ink-300">Loading…</p>}

      {rows && rows.length === 0 && (
        <Card>
          <CardContent className="py-10 text-center text-sm text-ink-300">
            No data for this period.
          </CardContent>
        </Card>
      )}

      {rows && rows.length > 0 && (
        <div className="overflow-hidden rounded-lg border border-paper-200">
          {/* Header */}
          <div className="flex items-center gap-3 bg-paper-100 px-3 py-2 text-xs font-medium uppercase tracking-wide text-ink-300">
            <span className="w-8 text-center">#</span>
            <span className="flex-1">Name</span>
            <span className="w-16 text-right">Vihars</span>
            <span className="w-16 text-right">Km</span>
          </div>

          {/* Top 10 rows */}
          {rows.slice(0, 10).map((row, i) => {
            const isMe = row.userId === me?.userId;
            return (
              <div
                key={row.userId}
                className={`flex items-center gap-3 px-3 py-3 ${
                  isMe ? 'bg-saffron-50 border-l-2 border-saffron' : 'border-b border-paper-100 bg-white'
                }`}
              >
                <span className={`w-8 text-center text-sm font-semibold tabular-nums ${
                  i === 0 ? 'text-saffron' : i === 1 ? 'text-ink-400' : i === 2 ? 'text-amber-600' : 'text-ink-300'
                }`}>
                  {i + 1}
                </span>
                <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold ${
                  isMe ? 'bg-saffron text-white' : 'bg-paper-200 text-ink-400'
                }`}>
                  {initials(row.fullName)}
                </div>
                <span className={`flex-1 truncate text-sm font-medium ${isMe ? 'text-saffron-700' : 'text-ink'}`}>
                  {row.fullName}{isMe && ' (you)'}
                </span>
                <span className="w-16 text-right text-xs tabular-nums text-ink-400">{row.viharCount}</span>
                <span className="w-16 text-right text-xs tabular-nums text-ink-500 font-medium">
                  {row.totalKm.toFixed(1)}
                </span>
              </div>
            );
          })}

          {/* Separator + user's row if outside top 10 */}
          {showMyRow && (
            <>
              <div className="py-2 text-center text-xs text-ink-200">· · ·</div>
              <div className="flex items-center gap-3 bg-saffron-50 border-l-2 border-saffron px-3 py-3">
                <span className="w-8 text-center text-sm font-semibold tabular-nums text-saffron">{myRank}</span>
                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-saffron text-white text-xs font-semibold">
                  {initials(myRow.fullName)}
                </div>
                <span className="flex-1 truncate text-sm font-medium text-saffron-700">
                  {myRow.fullName} (you)
                </span>
                <span className="w-16 text-right text-xs tabular-nums text-ink-400">{myRow.viharCount}</span>
                <span className="w-16 text-right text-xs tabular-nums text-ink-500 font-medium">
                  {myRow.totalKm.toFixed(1)}
                </span>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
}
