"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import type { CRMListFilterValue } from "@/components/crm/crm-list-filters";

function humanize(value: string) {
  return value
    .toLowerCase()
    .replaceAll("_", " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

const CRM_LIST_TARGETS = [
  { href: "/companies", label: "Companies" },
  { href: "/brokers", label: "Brokers" },
  { href: "/drivers", label: "Drivers" },
  { href: "/owner-operators", label: "Owner Ops" },
  { href: "/shippers", label: "Shippers" },
] as const;

export function CrmReportContextBanner({
  label,
  source,
  filters,
}: {
  label: string;
  source?: string | null;
  filters: CRMListFilterValue;
}) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const clearReportHref = (() => {
    const params = new URLSearchParams(searchParams.toString());
    params.delete("report");
    params.delete("source");
    const query = params.toString();
    return query ? `${pathname}?${query}` : pathname;
  })();

  const crossListLinks = CRM_LIST_TARGETS.map((target) => {
    const query = searchParams.toString();
    return {
      ...target,
      active: pathname === target.href,
      hrefWithContext: query ? `${target.href}?${query}` : target.href,
    };
  });

  const activeFilters = [
    filters.quickFilter !== "ALL" ? `Quick: ${humanize(filters.quickFilter)}` : null,
    filters.stage ? `Stage: ${humanize(filters.stage)}` : null,
    filters.status ? `Status: ${humanize(filters.status)}` : null,
    filters.search.trim() ? `Search: ${filters.search.trim()}` : null,
  ].filter(Boolean) as string[];

  return (
    <section className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div className="space-y-2">
          <div>
            <div className="text-sm font-semibold text-blue-900">Reporting filter carry-forward</div>
            <div className="mt-1 text-sm text-blue-800">
              You are viewing the <span className="font-semibold">{label}</span> report context{source ? ` from ${source.replaceAll("-", " ")}` : ""}. Filters stay on while switching lists.
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/crm" className="rounded-full border border-blue-200 bg-white px-3 py-1.5 text-xs font-medium text-blue-900 hover:bg-blue-100">
              Back to CRM
            </Link>
            <Link href={clearReportHref} className="rounded-full border border-blue-200 bg-white px-3 py-1.5 text-xs font-medium text-blue-900 hover:bg-blue-100">
              Clear report handoff
            </Link>
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          {activeFilters.length ? activeFilters.map((item) => (
            <span key={item} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-blue-800">{item}</span>
          )) : <span className="text-xs text-blue-800">No additional list filters are active.</span>}
        </div>
      </div>
      <div className="mt-3 flex flex-wrap gap-2">
        {crossListLinks.map((target) => (
          target.active ? (
            <span key={target.href} className="rounded-full border border-blue-300 bg-white px-3 py-1.5 text-xs font-semibold text-blue-900">{target.label}</span>
          ) : (
            <Link key={target.href} href={target.hrefWithContext} className="rounded-full border border-blue-200 bg-white px-3 py-1.5 text-xs font-medium text-blue-900 hover:bg-blue-100">
              Open {target.label}
            </Link>
          )
        ))}
      </div>
    </section>
  );
}
