'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

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

interface PersonalStats {
  period: { from: string; to: string };
  lifetime: { vihars: number; totalKm: number };
  current: { vihars: number; totalKm: number };
  comparison: { previousPeriodVihars: number; pctChange: number | null };
  rank: { position: number; total: number } | null;
  recentVihars: Array<{ viharId: number; date: string; from: string; to: string; distanceKm: number }>;
}

// ---- Tile -----------------------------------------------------------------

function Tile({ label, value, sub }: { label: string; value: string | number; sub?: string }) {
  return (
    <div className="flex flex-col rounded-lg border border-paper-200 bg-white p-3">
      <span className="text-xs font-medium uppercase tracking-wide text-ink-300">{label}</span>
      <span className="mt-1 text-2xl font-semibold tabular-nums text-ink">{value}</span>
      {sub && <span className="text-xs text-ink-300">{sub}</span>}
    </div>
  );
}

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

export default function VolunteerStatsPage() {
  const { data: monthly, isLoading } = useQuery<PersonalStats>({
    queryKey: ['myStats', 'this_month'],
    queryFn: () => api.get<PersonalStats>('/api/stats/me', { query: { period: 'this_month' } }),
  });

  const { data: lifetime } = useQuery<PersonalStats>({
    queryKey: ['myStats', 'lifetime'],
    queryFn: () => api.get<PersonalStats>('/api/stats/me', { query: { period: 'lifetime' } }),
  });

  if (isLoading) return <div className="py-20 text-center text-sm text-ink-300">Loading…</div>;

  const pct = monthly?.comparison.pctChange;
  const rankData = monthly?.rank ?? lifetime?.rank;

  return (
    <div className="space-y-5 pb-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">My Stats</h1>
      </div>

      {/* Big tiles */}
      <div>
        <p className="mb-2 text-xs font-medium uppercase tracking-wide text-ink-300">This month</p>
        <div className="grid grid-cols-2 gap-3">
          <Tile label="Vihars" value={monthly?.current.vihars ?? 0} />
          <Tile label="Distance" value={`${(monthly?.current.totalKm ?? 0).toFixed(1)} km`} />
        </div>
      </div>

      {/* Comparison badge */}
      {pct !== null && pct !== undefined && (
        <div className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium ${
          pct >= 0 ? 'bg-saffron-50 text-saffron-700' : 'bg-red-50 text-rust'
        }`}>
          {pct >= 0 ? '↑' : '↓'} {Math.abs(pct)}% vs last month
        </div>
      )}

      {/* Lifetime */}
      <div>
        <p className="mb-2 text-xs font-medium uppercase tracking-wide text-ink-300">Lifetime</p>
        <div className="grid grid-cols-2 gap-3">
          <Tile label="Total vihars" value={lifetime?.lifetime.vihars ?? 0} />
          <Tile label="Total distance" value={`${(lifetime?.lifetime.totalKm ?? 0).toFixed(1)} km`} />
        </div>
      </div>

      {/* Rank */}
      {rankData && (
        <Card className="bg-saffron-50 border-saffron-100">
          <CardContent className="py-3 text-center">
            <p className="text-2xl font-bold text-saffron">#{rankData.position}</p>
            <p className="text-sm text-saffron-700">of {rankData.total} volunteers in your city</p>
          </CardContent>
        </Card>
      )}

      {/* Recent vihars */}
      {monthly?.recentVihars && monthly.recentVihars.length > 0 && (
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base">Recent vihars</CardTitle>
          </CardHeader>
          <CardContent className="divide-y divide-paper-100 pt-0">
            {monthly.recentVihars.map((v) => (
              <div key={v.viharId} className="flex items-center justify-between py-2.5">
                <div>
                  <p className="text-sm text-ink">{v.from} → {v.to}</p>
                  <p className="text-xs text-ink-300">{v.date}</p>
                </div>
                <span className="text-xs font-medium text-moss-600">{v.distanceKm.toFixed(1)} km</span>
              </div>
            ))}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
