'use client';

import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { ChevronRight, Users } from 'lucide-react';
import { formatDistanceToNowStrict } from 'date-fns';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { apiFetch } from '@/lib/api/client';
import { stageBadgeClass, stageLabel } from '@/lib/constants';
import { computeUrgencyBadges } from '@/components/interests/urgency';
import type { InterestRow } from '@/components/interests/interest-columns';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { cn } from '@/lib/utils';

interface InterestsResponse {
  data: InterestRow[];
}

const PREVIEW_LIMIT = 5;

/**
 * Top-of-overview pulse for the berth detail page. Lists the active
 * interested parties with their stage + last activity, so the rep can do
 * berth-level triage ("who's on this slip and how warm are they?")
 * without clicking into the Interests tab.
 *
 * Borrows from the old Nuxt CRM's BerthDetailsModal "Interested Parties"
 * pattern but uses the new at-a-glance signals (urgency badges, last
 * activity).
 */
export function BerthInterestPulse({ berthId }: { berthId: string }) {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  const queryKey = ['interests', { berthId, sort: 'dateLastContact', order: 'desc' }];
  const { data, isLoading } = useQuery<InterestsResponse>({
    queryKey,
    queryFn: () =>
      apiFetch<InterestsResponse>(
        `/api/v1/interests?berthId=${berthId}&limit=10&sort=dateLastContact&order=desc`,
      ),
    staleTime: 30_000,
  });

  // Stay in sync with the linked-berths list + add-to-interest dialog.
  // Each of those flows emits a realtime socket event but does NOT
  // invalidate this exact query key (it's berth-scoped, theirs are
  // interest-scoped) - bridge via the invalidation hook.
  useRealtimeInvalidation({
    'interest:berthLinked': [queryKey],
    'interest:berthUnlinked': [queryKey],
    'interest:berthLinkUpdated': [queryKey],
    'interest:created': [queryKey],
    'interest:stageChanged': [queryKey],
    'interest:archived': [queryKey],
  });

  const all = data?.data ?? [];
  const active = all.filter((i) => !i.archivedAt && !i.outcome);
  const preview = active.slice(0, PREVIEW_LIMIT);
  const more = active.length - preview.length;

  if (isLoading) {
    return (
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-sm font-medium">Interested parties</CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="space-y-2">
            {[0, 1, 2].map((i) => (
              <div key={i} className="h-10 animate-pulse rounded-md bg-muted/40" />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (active.length === 0) {
    return (
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-1.5 text-sm font-medium">
            <Users className="size-3.5" aria-hidden />
            Interested parties
          </CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          <p className="text-sm text-muted-foreground">No active interests on this berth.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-3 space-y-0">
        <CardTitle className="flex items-center gap-1.5 text-sm font-medium">
          <Users className="size-3.5" aria-hidden />
          Interested parties
          <span className="ml-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
            {active.length}
          </span>
        </CardTitle>
      </CardHeader>
      <CardContent className="pt-0">
        <ul className="divide-y divide-border">
          {preview.map((i) => {
            const lastIso = i.dateLastContact ?? i.updatedAt ?? null;
            const lastActivity = lastIso
              ? formatDistanceToNowStrict(new Date(lastIso), { addSuffix: true })
              : null;
            const urgency = computeUrgencyBadges(i);
            const initials = (i.clientName ?? '?')
              .split(/\s+/)
              .filter(Boolean)
              .slice(0, 2)
              .map((p) => p[0]!.toUpperCase())
              .join('');
            return (
              <li key={i.id}>
                <Link
                  href={`/${portSlug}/interests/${i.id}`}
                  className="group flex items-center gap-3 px-1 py-2.5 transition-colors hover:bg-foreground/5 rounded-md -mx-1"
                >
                  <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-brand-100 text-xs font-semibold text-brand-700">
                    {initials || '?'}
                  </span>
                  <div className="min-w-0 flex-1 space-y-0.5">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="truncate text-sm font-medium text-foreground">
                        {i.clientName ?? 'Unknown'}
                      </span>
                      <span
                        className={cn(
                          'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
                          stageBadgeClass(i.pipelineStage),
                        )}
                      >
                        {stageLabel(i.pipelineStage)}
                      </span>
                      {urgency.map((b) => (
                        <span
                          key={b.id}
                          title={b.detail}
                          className={cn(
                            'inline-flex items-center rounded-full px-1.5 py-0.5 text-xs font-medium',
                            b.className,
                          )}
                        >
                          {b.label}
                        </span>
                      ))}
                    </div>
                    {lastActivity ? (
                      <p className="text-xs tabular-nums text-muted-foreground">
                        Last activity {lastActivity}
                      </p>
                    ) : null}
                  </div>
                  <ChevronRight
                    className="size-4 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5"
                    aria-hidden
                  />
                </Link>
              </li>
            );
          })}
        </ul>
        {more > 0 ? (
          <Link
            href={`/${portSlug}/berths/${berthId}?tab=interests`}
            className="mt-2 inline-flex text-xs font-medium text-primary hover:underline"
          >
            View all {active.length} interests →
          </Link>
        ) : null}
      </CardContent>
    </Card>
  );
}
