import { Link } from '@inertiajs/react';

import { cn } from '@/lib/utils';

interface LifecycleStatusFilterProps {
  counts: Record<string, number>;
  currentFilter: string | null;
  siteId: number;
  /** Preserve other active query params (action_type, sort) when switching lifecycle status */
  currentFilters?: { action_type?: string | null; sort?: string | null };
}

interface FilterPillProps {
  label: string;
  active: boolean;
  href: string;
  count: number;
}

const LIFECYCLE_STATUSES = [
  { value: 'pending', label: 'Pending' },
  { value: 'reviewed', label: 'Reviewed' },
  { value: 'approved', label: 'Approved' },
  { value: 'rejected', label: 'Rejected' },
  { value: 'deferred', label: 'Deferred' },
  { value: 'applied', label: 'Applied' },
  { value: 'tracking', label: 'Tracking' },
];

function FilterPill({ label, active, href, count }: FilterPillProps) {
  return (
    <Link
      href={href}
      className={cn(
        'inline-flex items-center rounded-full px-3 py-1.5 text-sm font-medium transition-colors',
        active
          ? 'bg-primary text-primary-foreground'
          : 'bg-muted text-muted-foreground hover:bg-muted/80',
        count === 0 && !active && 'opacity-50',
      )}
    >
      {label}
    </Link>
  );
}

function buildFilterUrl(
  baseUrl: string,
  params: Record<string, string | null | undefined>,
): string {
  const searchParams = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (value) {
      searchParams.set(key, value);
    }
  }
  const qs = searchParams.toString();
  return qs ? `${baseUrl}?${qs}` : baseUrl;
}

export default function LifecycleStatusFilter({
  counts,
  currentFilter,
  siteId,
  currentFilters,
}: LifecycleStatusFilterProps) {
  const baseUrl = route('recommendations.index', siteId);
  const otherParams = {
    action_type: currentFilters?.action_type,
    sort: currentFilters?.sort,
  };

  return (
    <div className="flex flex-wrap gap-2">
      <FilterPill
        label={`All (${counts.total ?? 0})`}
        active={!currentFilter}
        href={buildFilterUrl(baseUrl, { ...otherParams })}
        count={counts.total ?? 0}
      />
      {LIFECYCLE_STATUSES.map((status) => (
        <FilterPill
          key={status.value}
          label={`${status.label} (${counts[status.value] ?? 0})`}
          active={currentFilter === status.value}
          href={buildFilterUrl(baseUrl, { lifecycle_status: status.value, ...otherParams })}
          count={counts[status.value] ?? 0}
        />
      ))}
    </div>
  );
}
