"use client";

import { Tag as TagIcon, Check, Ban } from "lucide-react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/app/shadcn_components/ui/popover";
import { usePortfolioTags } from "@/app/portfolio/[slug]/components/useTags";
import { TagChip } from "@/app/portfolio/[slug]/components/TagChip";
import type { TagFilter, IncludeMode } from "@/lib/reporting/viewState";

/**
 * The reporting tag filter (view-wide). Each tag can be Included (home must
 * carry it) or Excluded (home must not) — mutually exclusive per tag. When two
 * or more tags are included, an Any/All switch chooses union vs intersection.
 * Purely presentational + local wiring: it hands a new {@link TagFilter} up to
 * the parent, which pushes it into the URL.
 */
export function TagFilterControl({
  portfolioId,
  value,
  onChange,
}: {
  portfolioId: number;
  value: TagFilter;
  onChange: (next: TagFilter) => void;
}) {
  const { data: tags = [], isLoading } = usePortfolioTags(String(portfolioId));
  const activeCount = value.include.length + value.exclude.length;

  const toggleInclude = (id: string) =>
    onChange({
      ...value,
      include: value.include.includes(id)
        ? value.include.filter((x) => x !== id)
        : [...value.include, id],
      exclude: value.exclude.filter((x) => x !== id),
    });

  const toggleExclude = (id: string) =>
    onChange({
      ...value,
      exclude: value.exclude.includes(id)
        ? value.exclude.filter((x) => x !== id)
        : [...value.exclude, id],
      include: value.include.filter((x) => x !== id),
    });

  const setMode = (includeMode: IncludeMode) =>
    onChange({ ...value, includeMode });

  const clear = () =>
    onChange({ include: [], exclude: [], includeMode: "any" });

  const trigger = (
    <button
      type="button"
      aria-haspopup="dialog"
      className={`inline-flex h-8 items-center gap-1.5 rounded-lg border px-3 text-sm font-medium ${
        activeCount > 0
          ? "border-brandblue bg-[#f2f3f9] text-brandblue"
          : "border-gray-200 bg-white text-gray-600 hover:border-gray-300"
      }`}
    >
      <TagIcon className="h-3.5 w-3.5" />
      Tags
      {activeCount > 0 && (
        <span className="ml-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-brandblue px-1 text-[0.62rem] font-bold text-white">
          {activeCount}
        </span>
      )}
    </button>
  );

  return (
    <Popover>
      <PopoverTrigger asChild>{trigger}</PopoverTrigger>
      <PopoverContent align="end" className="w-[22rem] p-0">
        <div className="flex items-center justify-between border-b border-gray-100 px-3.5 py-2.5">
          <span className="text-[0.8rem] font-semibold text-brandblue">
            Filter by tag
          </span>
          {activeCount > 0 && (
            <button
              type="button"
              onClick={clear}
              className="text-[0.72rem] font-medium text-midblue hover:underline"
            >
              Clear
            </button>
          )}
        </div>

        {value.include.length >= 2 && (
          <div className="flex items-center gap-2 border-b border-gray-100 px-3.5 py-2 text-[0.74rem]">
            <span className="text-gray-500">Match</span>
            <div className="inline-flex overflow-hidden rounded-md border border-gray-200">
              {(["any", "all"] as const).map((m) => (
                <button
                  key={m}
                  type="button"
                  aria-pressed={value.includeMode === m}
                  onClick={() => setMode(m)}
                  className={`px-2.5 py-1 font-medium ${
                    value.includeMode === m
                      ? "bg-brandblue text-white"
                      : "bg-white text-gray-600 hover:bg-gray-50"
                  }`}
                >
                  {m === "any" ? "any" : "all"}
                </button>
              ))}
            </div>
            <span className="text-gray-500">of the included tags</span>
          </div>
        )}

        <div className="max-h-72 overflow-y-auto py-1">
          {isLoading ? (
            <p className="px-3.5 py-3 text-[0.78rem] text-gray-500">
              Loading tags…
            </p>
          ) : tags.length === 0 ? (
            <p className="px-3.5 py-3 text-[0.78rem] text-gray-500">
              This portfolio has no tags yet.
            </p>
          ) : (
            tags.map((t) => {
              const included = value.include.includes(t.id);
              const excluded = value.exclude.includes(t.id);
              return (
                <div
                  key={t.id}
                  className="flex items-center gap-2 px-3.5 py-1.5 hover:bg-gray-50"
                >
                  <span className="min-w-0 flex-1">
                    <TagChip name={t.name} colour={t.colour} />
                    <span className="ml-1.5 text-[0.68rem] tabular-nums text-gray-400">
                      {t.propertyCount}
                    </span>
                  </span>
                  <button
                    type="button"
                    aria-pressed={included}
                    onClick={() => toggleInclude(t.id)}
                    className={`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-[0.72rem] font-medium ${
                      included
                        ? "border-[#0c6b4a] bg-[#e9f4ef] text-[#0c6b4a]"
                        : "border-gray-200 bg-white text-gray-500 hover:border-gray-300"
                    }`}
                  >
                    <Check className="h-3 w-3" />
                    Include
                  </button>
                  <button
                    type="button"
                    aria-pressed={excluded}
                    onClick={() => toggleExclude(t.id)}
                    className={`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-[0.72rem] font-medium ${
                      excluded
                        ? "border-[#b91c1c] bg-[#fbeaea] text-[#b91c1c]"
                        : "border-gray-200 bg-white text-gray-500 hover:border-gray-300"
                    }`}
                  >
                    <Ban className="h-3 w-3" />
                    Exclude
                  </button>
                </div>
              );
            })
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
