"use client";

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

type Shortcut = { label: string; href: string; tone?: string };

function filterSummary(filters: CRMListFilterValue) {
  return [
    filters.quickFilter !== "ALL" ? `Quick ${filters.quickFilter.replaceAll("_", " ").toLowerCase()}` : null,
    filters.stage ? `Stage ${filters.stage.replaceAll("_", " ").toLowerCase()}` : null,
    filters.status ? `Status ${filters.status.toLowerCase()}` : null,
    filters.search.trim() ? `Search ${filters.search.trim()}` : null,
  ].filter(Boolean) as string[];
}

export function CrmListActionBar({
  entityLabel,
  createHref,
  createLabel,
  canManage,
  totalCount,
  filteredCount,
  hotCount,
  activeCount,
  dueCount,
  filters,
  shortcuts,
  showCrmHandoff = true,
}: {
  entityLabel: string;
  createHref: string;
  createLabel: string;
  canManage: boolean;
  totalCount: number;
  filteredCount: number;
  hotCount: number;
  activeCount: number;
  dueCount: number;
  filters: CRMListFilterValue;
  shortcuts: Shortcut[];
  showCrmHandoff?: boolean;
}) {
  const activeFilters = filterSummary(filters);
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const query = searchParams.toString();
  const carriedContext = [searchParams.get("report") ? `Report ${searchParams.get("report")}` : null, searchParams.get("source") ? `Source ${searchParams.get("source")}` : null].filter(Boolean) as string[];
  const overviewTargets = [
    { label: "CRM Overview", href: "/crm" },
    { label: "Ask CORI", href: "/cori?source=crm&question=Help me choose the best CRM follow-up." },
    { label: "CORI's Quotes", href: "/cori/quotes" },
  ];
  const crossListTargets = [
    { label: "Companies", href: "/companies" },
    { label: "Brokers", href: "/brokers" },
    { label: "Shippers", href: "/shippers" },
  ];
  return (
    <section className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="space-y-3">
          <div>
            <div className="text-sm font-semibold text-gray-900">Quick actions</div>
            <div className="mt-1 text-xs text-gray-500">Shortcuts for the {entityLabel.toLowerCase()} list.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Showing {filteredCount}</span>
            <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Total {totalCount}</span>
            <span className="rounded-full bg-red-50 px-2.5 py-1 text-xs font-medium text-red-700">Due {dueCount}</span>
            <span className="rounded-full bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-700">Hot {hotCount}</span>
            <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700">Active {activeCount}</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {shortcuts.map((shortcut) => (
              <Link key={shortcut.label} href={shortcut.href} className={`rounded-full border px-3 py-1.5 text-xs font-medium hover:bg-gray-100 ${shortcut.tone ?? "bg-white text-gray-700"}`}>
                {shortcut.label}
              </Link>
            ))}
            {canManage ? <Link href={createHref} className="rounded-full bg-black px-3 py-1.5 text-xs font-medium text-white">{createLabel}</Link> : null}
          </div>
        </div>
        <div className="space-y-3 xl:max-w-sm">
          <div className="rounded-xl border bg-gray-50 p-3">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Current filters</div>
                <div className="mt-1 text-xs text-gray-500">Use filters to narrow this list without leaving the page.</div>
              </div>
              {query ? <Link href={pathname} className="rounded-full border bg-white px-2.5 py-1 text-[11px] font-medium text-gray-700 hover:bg-gray-100">Clear carried context</Link> : null}
            </div>
            <div className="mt-2 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-gray-700">{item}</span>
              )) : <span className="text-xs text-gray-500">No extra filters applied.</span>}
              {carriedContext.map((item) => (
                <span key={item} className="rounded-full bg-blue-50 px-2.5 py-1 text-xs font-medium text-blue-700">{item}</span>
              ))}
            </div>
          </div>
          {showCrmHandoff ? (
          <div className="space-y-3 rounded-xl border border-blue-200 bg-blue-50 p-3">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-wide text-blue-900">CRM links</div>
                <div className="mt-1 text-xs text-blue-800">Move between company, broker, and shipper lists without losing the current context.</div>
              </div>
              <div className="flex flex-wrap gap-2">
                {overviewTargets.map((target) => {
                  const active = pathname === target.href;
                  return 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.href} 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>
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-wide text-blue-900">Switch lists</div>
                <div className="mt-1 text-xs text-blue-800">Move between CRM lists while keeping the same filter context attached.</div>
                <div className="mt-2 flex flex-wrap gap-2">
                  {crossListTargets.map((target) => {
                    const href = query ? `${target.href}?${query}` : target.href;
                    const active = pathname === target.href;
                    return 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={href} 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>
              </div>
            </div>
  
          ) : null}
        </div>
      </div>
    </section>
  );
}
