'use client';

import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import type { Route } from 'next';
import { useParams } from 'next/navigation';
import { TrendingUp } from 'lucide-react';

import { apiFetch } from '@/lib/api/client';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';

interface KpiResponse {
  totalClients: number;
  activeInterests: number;
  pipelineValue: number;
  pipelineValueCurrency: string;
  occupancyRate: number;
}

/**
 * Compact rail-sized KPI tile - single number, label, and a click-
 * through to the interests pipeline. Reuses the existing dashboard KPIs
 * endpoint so we don't pay an extra round-trip.
 */
export function ActiveDealsTile() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const { data, isLoading } = useQuery<KpiResponse>({
    queryKey: ['dashboard', 'kpis'],
    queryFn: () => apiFetch<KpiResponse>('/api/v1/dashboard/kpis'),
    staleTime: 60_000,
  });

  return (
    <Card>
      {/* shadcn's default CardContent ships with `pt-0 sm:pt-0` (it assumes a
          CardHeader sits above). The `sm:` variants are required - without
          them `sm:pt-0` wins at the sm breakpoint and the content snaps to
          the top edge. */}
      <CardContent className="flex items-center gap-3 pt-5 pb-5 sm:pt-5 sm:pb-5">
        <div className="flex size-10 shrink-0 items-center justify-center rounded-md bg-accent text-foreground">
          <TrendingUp className="size-5" aria-hidden />
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
            Active deals
          </p>
          {isLoading ? (
            <Skeleton className="mt-1 h-7 w-12" aria-hidden />
          ) : (
            <p className="text-2xl font-bold leading-tight text-foreground">
              {data?.activeInterests ?? 0}
            </p>
          )}
        </div>
        <Link
          // Next typedRoutes can't infer dynamic-segment routes from a template
          // literal - cast through unknown rather than `any` so the lint rule
          // is satisfied while the runtime href is still correct.
          href={`/${portSlug}/interests` as unknown as Route}
          className="text-xs font-medium text-primary hover:underline"
        >
          View
        </Link>
      </CardContent>
    </Card>
  );
}
