"use client";

import { X, ChevronDown } from "lucide-react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/app/shadcn_components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/app/shadcn_components/ui/select";
import { EPC_BANDS } from "@/lib/epc/bands";
import { InfoDot } from "./primitives";
import { TipBody, type TipSpec } from "./tipContent";

/** Structured "what this filter does" copy — same shape/look as the cost ⓘs. */
const FILTER_HELP: Record<
  "reachTarget" | "lodgedBaseline" | "complianceWindow",
  TipSpec
> = {
  reachTarget: {
    summary:
      "Counts only homes whose modelled result reaches this scenario's target band.",
    note: "Homes still short of target after the works drop out of every figure, so costs and outcomes cover the fully-compliant homes only.",
  },
  lodgedBaseline: {
    summary:
      "Decides which homes need work from their official lodged EPC band on the government register, not Domna's modelled current band.",
    note: "Use it to match what the register says a home needs.",
  },
  complianceWindow: {
    summary:
      "Leaves out homes whose official (lodged) EPC already meets the band below and stays valid past the date.",
    note: "The government counts these as compliant beyond then, so costs and outcomes show only the works on the remaining homes.",
  },
};

/**
 * Inline scenario filter chips (Screen B). State is always visible and
 * applies immediately — no apply step. Each chip carries a plain-language
 * explanation; the compliance-window chip opens a small editor for its band
 * and cut-off date. Shown only for Increasing-EPC scenarios, where these
 * filters have meaning.
 */
export interface ScenarioFilters {
  hideNonCompliant: boolean;
  useLodgedBaseline: boolean;
  complianceWindow: { band: string; date: string } | null;
}

const DEFAULT_COMPLIANCE = { band: "C", date: "2030-01-01" };

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}

/** A toggle chip with an info tooltip explaining what it does. */
function ToggleChip({
  on,
  onToggle,
  label,
  tip,
}: {
  on: boolean;
  onToggle: () => void;
  label: string;
  tip: React.ReactNode;
}) {
  return (
    <span
      className={`inline-flex h-7 items-center gap-1.5 rounded-full border pl-3 pr-2 text-[0.76rem] ${
        on
          ? "border-brandblue bg-[#f2f3f9] font-medium text-brandblue"
          : "border-gray-200 bg-white text-gray-500"
      }`}
    >
      <button
        type="button"
        onClick={onToggle}
        aria-pressed={on}
        className="flex items-center gap-1.5"
      >
        {label}
        {on && <X className="h-3 w-3 text-gray-600" />}
      </button>
      <InfoDot label={label} tip={tip} />
    </span>
  );
}

export function FilterChips({
  filters,
  onChange,
  showEpcFilters,
}: {
  filters: ScenarioFilters;
  onChange: (next: ScenarioFilters) => void;
  showEpcFilters: boolean;
}) {
  if (!showEpcFilters) return null;

  const cw = filters.complianceWindow;

  return (
    <div className="flex flex-wrap items-center gap-2">
      <span className="text-[0.7rem] font-semibold uppercase tracking-wide text-gray-600">
        Filters
      </span>

      <ToggleChip
        on={filters.hideNonCompliant}
        onToggle={() =>
          onChange({ ...filters, hideNonCompliant: !filters.hideNonCompliant })
        }
        label="Only homes that reach target"
        tip={<TipBody spec={FILTER_HELP.reachTarget} />}
      />

      {/* Compliance window — editable band + date */}
      <Popover>
        <PopoverTrigger asChild>
          <button
            type="button"
            className={`inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[0.76rem] ${
              cw
                ? "border-brandblue bg-[#f2f3f9] font-medium text-brandblue"
                : "border-gray-200 bg-white text-gray-500 hover:border-gray-300"
            }`}
          >
            {cw
              ? `Skip homes compliant past ${formatDate(cw.date)} at ${cw.band}+`
              : "Skip already-compliant homes"}
            <ChevronDown className="h-3 w-3 text-gray-600" />
          </button>
        </PopoverTrigger>
        <PopoverContent align="end" className="w-80 p-4">
          <div className="text-[0.82rem] font-semibold text-brandblue">
            Skip already-compliant homes
          </div>
          <div className="mt-1.5 text-[0.78rem] leading-relaxed">
            <TipBody spec={FILTER_HELP.complianceWindow} />
          </div>

          <label className="mt-3 flex items-center gap-2 text-[0.8rem] text-gray-700">
            <input
              type="checkbox"
              checked={!!cw}
              onChange={(e) =>
                onChange({
                  ...filters,
                  complianceWindow: e.target.checked
                    ? (cw ?? DEFAULT_COMPLIANCE)
                    : null,
                })
              }
              className="h-4 w-4 rounded border-gray-300 accent-brandblue"
            />
            Apply this filter
          </label>

          <div className="mt-3 grid grid-cols-2 gap-3">
            <div>
              <div className="mb-1 text-[0.68rem] font-semibold uppercase tracking-wide text-gray-600">
                Compliant at band
              </div>
              <Select
                value={(cw ?? DEFAULT_COMPLIANCE).band}
                onValueChange={(band) =>
                  onChange({
                    ...filters,
                    complianceWindow: { ...(cw ?? DEFAULT_COMPLIANCE), band },
                  })
                }
              >
                <SelectTrigger className="h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {EPC_BANDS.map((b) => (
                    <SelectItem key={b} value={b}>
                      {b} or better
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <div className="mb-1 text-[0.68rem] font-semibold uppercase tracking-wide text-gray-600">
                Still valid past
              </div>
              <input
                type="date"
                value={(cw ?? DEFAULT_COMPLIANCE).date}
                onChange={(e) =>
                  onChange({
                    ...filters,
                    complianceWindow: {
                      ...(cw ?? DEFAULT_COMPLIANCE),
                      date: e.target.value,
                    },
                  })
                }
                className="h-9 w-full rounded-md border border-gray-200 px-2 text-[0.8rem] text-gray-700"
              />
            </div>
          </div>
        </PopoverContent>
      </Popover>

      <ToggleChip
        on={filters.useLodgedBaseline}
        onToggle={() =>
          onChange({
            ...filters,
            useLodgedBaseline: !filters.useLodgedBaseline,
          })
        }
        label="Judge need by lodged EPC"
        tip={<TipBody spec={FILTER_HELP.lodgedBaseline} />}
      />
    </div>
  );
}
