'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { fmtDate } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import type { ViharStatusT } from '@vihar/shared';

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

interface ViharItem {
  viharId: number;
  viharDate: string;
  plannedStartTime: string;
  headSaintName: string;
  status: ViharStatusT;
  actualDistanceKm?: number | null;
  departureLocation: { name: string };
  arrivalLocation: { name: string };
  _count: { allocations: number };
}

interface ListResponse { items: ViharItem[]; total: number; page: number; pageSize: number }

const PAGE_SIZE = 20;

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

export default function VolunteerHistoryPage() {
  const router = useRouter();
  const [page, setPage] = useState(1);

  const { data, isLoading } = useQuery<ListResponse>({
    queryKey: ['my-vihars', page],
    queryFn: () =>
      api.get<ListResponse>('/api/vihars', {
        query: {
          mine: true,
          page,
          pageSize: PAGE_SIZE,
        },
      }),
    placeholderData: (prev: ListResponse | undefined) => prev,
  });

  const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 1;

  return (
    <div className="space-y-4 pb-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">My Vihar History</h1>
        {data && <p className="mt-0.5 text-sm text-ink-300">{data.total} completed vihar{data.total !== 1 ? 's' : ''}</p>}
      </div>

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

      {data && data.items.length === 0 && (
        <Card>
          <CardContent className="py-12 text-center text-sm text-ink-300">
            No completed vihars yet.
          </CardContent>
        </Card>
      )}

      {data && data.items.length > 0 && (
        <div className="space-y-2">
          {data.items.map((v) => (
            <button
              key={v.viharId}
              onClick={() => router.push(`/volunteer/vihars/${v.viharId}`)}
              className="flex w-full flex-col gap-1 rounded-lg border border-paper-200 bg-white px-4 py-3 text-left transition-colors hover:bg-paper-50"
            >
              <div className="flex items-start justify-between gap-2">
                <p className="text-sm font-medium text-ink">
                  {v.departureLocation.name} → {v.arrivalLocation.name}
                </p>
                {v.actualDistanceKm != null && (
                  <span className="shrink-0 text-xs font-medium text-moss-600">
                    {v.actualDistanceKm.toFixed(1)} km
                  </span>
                )}
              </div>
              <p className="text-xs text-ink-300">
                {fmtDate(v.viharDate)} · {v.headSaintName}
              </p>
            </button>
          ))}
        </div>
      )}

      {data && totalPages > 1 && (
        <div className="flex items-center justify-between pt-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p: number) => Math.max(1, p - 1))}
            disabled={page === 1}
          >
            ← Prev
          </Button>
          <span className="text-sm text-ink-300">Page {page} of {totalPages}</span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p: number) => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
          >
            Next →
          </Button>
        </div>
      )}
    </div>
  );
}
