'use client';

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

import { apiFetch } from '@/lib/api/client';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
import {
  PIPELINE_STAGES,
  STAGE_BADGE,
  STAGE_DOT,
  STAGE_LABELS,
  safeStage,
  type PipelineStage,
} from '@/components/clients/pipeline-constants';

export interface ClientInterestRow {
  id: string;
  pipelineStage: string;
  archivedAt: string | null;
  updatedAt: string;
  dateLastContact: string | null;
  berthMooringNumber?: string | null;
  yachtName?: string | null;
}

interface InterestsResponse {
  data: ClientInterestRow[];
}

export function useClientInterests(clientId: string) {
  return useQuery<InterestsResponse>({
    queryKey: ['interests', { clientId }],
    queryFn: () => apiFetch<InterestsResponse>(`/api/v1/interests?clientId=${clientId}&limit=50`),
  });
}

export function StageStepper({
  current,
  size = 'sm',
}: {
  current: PipelineStage;
  size?: 'xs' | 'sm';
}) {
  const idx = PIPELINE_STAGES.indexOf(current);
  // Segmented progress bar: each stage is a slice of equal width that
  // lights up once the interest has reached it. Reads at-a-glance, scales
  // to any container width, and works with 9 stages without becoming
  // micro-dots that vanish under cramped layouts.
  const height = size === 'xs' ? 'h-1' : 'h-1.5';
  return (
    <div
      className={cn('flex w-full overflow-hidden rounded-full bg-muted', height)}
      role="progressbar"
      aria-label="Pipeline progress"
      aria-valuenow={idx + 1}
      aria-valuemin={1}
      aria-valuemax={PIPELINE_STAGES.length}
    >
      {PIPELINE_STAGES.map((stage, i) => {
        const isReached = i <= idx;
        const isCurrent = i === idx;
        return (
          <div
            key={stage}
            title={`${STAGE_LABELS[stage]}${isCurrent ? ' (current)' : ''}`}
            className={cn(
              'flex-1 transition-colors',
              isReached ? STAGE_DOT[stage] : 'bg-transparent',
              i > 0 ? 'border-l border-card' : '',
            )}
          />
        );
      })}
    </div>
  );
}

function pickHighest(interests: ClientInterestRow[]): ClientInterestRow | null {
  const active = interests.filter((i) => !i.archivedAt);
  if (active.length === 0) return null;
  return [...active].sort((a, b) => {
    const ai = PIPELINE_STAGES.indexOf(safeStage(a.pipelineStage));
    const bi = PIPELINE_STAGES.indexOf(safeStage(b.pipelineStage));
    if (ai !== bi) return bi - ai;
    return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
  })[0]!;
}

function lastActivityLabel(interests: ClientInterestRow[]): string | null {
  const candidates = interests
    .flatMap((i) => [i.dateLastContact, i.updatedAt])
    .filter((v): v is string => Boolean(v))
    .map((v) => new Date(v).getTime())
    .filter((t) => !Number.isNaN(t));
  if (candidates.length === 0) return null;
  const latest = new Date(Math.max(...candidates));
  return `${formatDistanceToNowStrict(latest)} ago`;
}

interface PipelineSummaryProps {
  clientId: string;
  /**
   * `hero` - single-line pulse for the detail header (highest active stage only).
   * `panel` - compact list of every active interest, for the Overview tab.
   */
  variant?: 'hero' | 'panel';
}

function HeroVariant({ clientId, portSlug }: { clientId: string; portSlug: string }) {
  const pathname = usePathname();
  const { data, isLoading } = useClientInterests(clientId);
  const interests = data?.data ?? [];
  const top = pickHighest(interests);
  const activeCount = interests.filter((i) => !i.archivedAt).length;
  const activity = lastActivityLabel(interests);
  const interestsTabHref = `${pathname}?tab=interests` as Route;

  if (isLoading) {
    return (
      <div className="space-y-2">
        <Skeleton className="h-4 w-40" />
        <Skeleton className="h-2 w-48" />
      </div>
    );
  }

  if (!top) {
    return (
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <p className="text-sm font-medium text-foreground">No active interests</p>
          <p className="text-xs text-muted-foreground">
            Start one to begin tracking the sales process.
          </p>
        </div>
        <Link
          href={`/${portSlug}/interests/new` as Route}
          className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
        >
          Start interest <ArrowRight className="size-3" />
        </Link>
      </div>
    );
  }

  const stage = safeStage(top.pipelineStage);
  const berthLabel = top.berthMooringNumber
    ? `Berth ${top.berthMooringNumber}`
    : 'General interest';
  const detailsHref = `/${portSlug}/interests/${top.id}` as Route;

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
          Sales pipeline
        </span>
        {activeCount > 1 ? (
          <span className="text-[10px] font-medium text-muted-foreground">
            · {activeCount} active
          </span>
        ) : null}
      </div>

      <Link
        href={detailsHref}
        className="group -m-1 block rounded-lg p-1 transition-colors hover:bg-foreground/5"
      >
        <div className="flex items-center gap-2 flex-wrap">
          <span className="truncate text-sm font-semibold text-foreground">{berthLabel}</span>
          <span
            className={cn(
              'shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium',
              STAGE_BADGE[stage],
            )}
          >
            {STAGE_LABELS[stage]}
          </span>
          <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
        </div>
        <div className="mt-1.5">
          <StageStepper current={stage} size="xs" />
        </div>
      </Link>

      <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
        <span>{activity ? `Last activity ${activity}` : 'No activity recorded'}</span>
        {activeCount > 1 ? (
          <Link
            href={interestsTabHref}
            className="font-medium text-primary hover:underline"
            scroll={false}
          >
            View all {activeCount}
          </Link>
        ) : null}
      </div>
    </div>
  );
}

function PanelVariant({ clientId, portSlug }: { clientId: string; portSlug: string }) {
  const pathname = usePathname();
  const { data, isLoading } = useClientInterests(clientId);
  const interests = (data?.data ?? []).filter((i) => !i.archivedAt);
  const interestsTabHref = `${pathname}?tab=interests` as Route;

  if (isLoading) {
    return (
      <div className="space-y-2">
        <Skeleton className="h-4 w-40" />
        <Skeleton className="h-2 w-48" />
      </div>
    );
  }

  if (interests.length === 0) {
    return (
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <p className="text-sm font-medium text-foreground">No active interests</p>
          <p className="text-xs text-muted-foreground">
            Start one to begin tracking the sales process.
          </p>
        </div>
        <Link
          href={`/${portSlug}/interests/new` as Route}
          className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
        >
          Start interest <ArrowRight className="size-3" />
        </Link>
      </div>
    );
  }

  const sorted = [...interests].sort(
    (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
  );

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between gap-2">
        <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
          Sales pipeline · {interests.length} active
        </span>
        <Link
          href={interestsTabHref}
          className="text-xs font-medium text-primary hover:underline"
          scroll={false}
        >
          Manage
        </Link>
      </div>

      <ul className="space-y-2">
        {sorted.map((i) => {
          const stage = safeStage(i.pipelineStage);
          const berthLabel = i.berthMooringNumber
            ? `Berth ${i.berthMooringNumber}`
            : 'General interest';
          const href = `/${portSlug}/interests/${i.id}` as Route;
          return (
            <li key={i.id}>
              <Link
                href={href}
                className="group flex items-center gap-3 rounded-lg p-2 -m-2 transition-colors hover:bg-foreground/5"
              >
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="truncate text-sm font-medium text-foreground">
                      {berthLabel}
                    </span>
                    <span
                      className={cn(
                        'shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium',
                        STAGE_BADGE[stage],
                      )}
                    >
                      {STAGE_LABELS[stage]}
                    </span>
                  </div>
                  <div className="mt-1">
                    <StageStepper current={stage} size="xs" />
                  </div>
                </div>
                <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
              </Link>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

export function ClientPipelineSummary({ clientId, variant = 'panel' }: PipelineSummaryProps) {
  const routeParams = useParams<{ portSlug: string }>();
  const portSlug = routeParams?.portSlug ?? '';

  return variant === 'hero' ? (
    <HeroVariant clientId={clientId} portSlug={portSlug} />
  ) : (
    <PanelVariant clientId={clientId} portSlug={portSlug} />
  );
}
